天天看點

componentscan注解的用法和作用_Spring新注解及Spring整合junit

@Configuration

  • 作用:指定目前類是一個配置類,等同于bean.xml
  • 細節:當配置類作為AnnotationConfigApplicationContext對象建立的參數時,該注解可以不寫,這時系統将直接掃描該配置類。
//1.擷取容器ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
           
//AnnotationConfigApplicationContext     被springConfiguration注解過的類        /**         *     public AnnotationConfigApplicationContext(Class>... annotatedClasses) {         *         this();         *         this.register(annotatedClasses);         *         this.refresh();         *     }         */
           

@ComponentScan

  • 作用:用于通過注解指定spring在建立容器時要掃描的包
  • 屬性:value,basePackages(兩個屬性别名互相引用,是以作用相同)指定要掃描的包

使用注解@ComponentScan(basePackages = {"com.itheima"})作用就等同于在xml中配置了

@Bean

  • 作用:用于把目前方法的傳回值作為bean對象存入spring的ioc容器中
  • 屬性:name:用于指定bean的id,當不寫時,預設值是目前方法的名稱
  • 細節:當使用注解配置方法時,如果方法有參數,spring會去容器中查找有沒有可用的bean對象。查找的方式和Autowired相同,根據類型比對,有一個注入成功,沒有注入失敗,有多個會找bean的id和該參數名相同的進行比對,如果有多個,可以在參數前使用@Qualifier("")注解指定容器中的bean(單獨使用的情況)。

@Import

  • 作用:導入其他的配置類。
  • 屬性:value:指定其他配置類的位元組碼。 

  使用方法:@Import(xxxx.class) //xxxx為導入的配置類名

  使用了Import注解後,有Import注解的為父配置類,而導入的都是子配置類。

@PropertySource  

  • 作用:用于指定properties檔案的位置
  • 屬性:value:指定檔案的名稱和路徑
  • 關鍵字:classpath:表示類路徑下

簡單例子

componentscan注解的用法和作用_Spring新注解及Spring整合junit

父配置類

//@Configuration//@ComponentScan(basePackages = "com.itheima")//@ComponentScan(basePackages = {"com.itheima"})//數組類型String[]//@ComponentScan({"com.itheima","config"})@ComponentScan("com.itheima")@Import(JdbcConfig.class)//classpath:表示後面的路徑是一個類路徑,指引jdbcConfig.properties加載//@PropertySource("classpath:com/itheima/jdbcConfig.properties")// 有包可以寫classpath:com/itheima/jdbcConfig.properties 沒包直接檔案名寫即可@PropertySource("classpath:jdbcConfig.properties")public class SpringConfiguration {}
           

子配置類

/** * 和spring連接配接資料庫相關的配置類 *///@Configurationpublic class JdbcConfig {    //spring的el表達式${}    @Value("${jdbc.driver}") //jdbc.driver表示.properties中的key,等着spring給我們擷取出value    private String driver;    @Value("${jdbc.url}")    private String url;    @Value("${jdbc.username}")    private String username;    @Value("${jdbc.password}")    private String password;    /**     * 用于建立一個QueryRunner對象     * @param dataSource     * @return     */    @Bean(name = "runner")    @Scope("prototype") //細節  :要改為多例對象。預設是單例    public QueryRunner createQueryRunner(DataSource dataSource){        return new QueryRunner(dataSource);    }    /**     * 建立資料源對象     * @return     */    @Bean(name = "dataSource")    public DataSource createDataSource(){        try {            ComboPooledDataSource ds = new ComboPooledDataSource();            ds.setDriverClass(driver);            ds.setJdbcUrl(url);            ds.setUser(username);            ds.setPassword(password);            return ds;        }catch (Exception e){            throw new RuntimeException(e);        }    }}
           

jdbcConfig.properties

jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/eesy_spring?serverTimezone=UTCjdbc.username=rootjdbc.password=123456
           

測試類

public class AccountServiceTest {    @Autowired    private IAccountService as = null; @Test    public void testFindOne() {      //1.擷取容器        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);        //2.得到業務層對象        IAccountService as = ac.getBean("accountService",IAccountService.class);        //3.執行方法        Account account = as.findAccountById(1);        System.out.println(account);    } }
           

運作結果

componentscan注解的用法和作用_Spring新注解及Spring整合junit

Spring整合junit配置

使用Junit單元測試:測試我們的配置

使用步驟

1、導入spring整合junit的坐标    spring-test坐标
           
2、使用junit提供的一個注解把原有的main方法替換了,替換成spring提供的
           
@RunWith
           
@RunWith(SpringJUnit4ClassRunner.class)
           
3、告知spring的運作器,spring的ioc建立是基于xml還是注解的,并且說明位置
           
@ContextConfiguration
           
Locations:指定xml檔案的位置,加上classpath關鍵字,表示在類路徑下classes:指定注解類所在的位置
           
當我們使用spring 5.x版本的時候,要求junit的jar必須是4.12及以上
           

測試類

運作結果

componentscan注解的用法和作用_Spring新注解及Spring整合junit

繼續閱讀