Spring 註解配置類基礎

Spring一般都是寫xml配置文件,其實也並不一定需要配置文件,使用註解可去除配置文件實現註解配置,簡單的複習回顧一下

我們首先定義一個類,名爲SpringConfiguration,裏面什麼都不用寫

public class SpringConfiguration {

}

然後我們來認識幾個Spring的註解

@Configuration註解

指定當前類是一個配置類,當配置類作爲AnootationConfigApplicationContext對象創建的參數時,可以不寫

@ComponentScan註解

用於通過註解指定Spring在創建容器時要掃描的包,和basePackeage作用一樣,等同於配置文件中配置了<context:conponent-scan base-package=""/>

@Bean

把當前方法的返回值作爲bean存入IOC容器中,其name屬性代表bean的id,不寫默認值是當前方法的名稱,和Autowired註解的作用一樣

@PropertySource

用於指定properties配置文件的位置,其屬性value指定文件的名稱和路徑,關鍵字:classpath表示類路徑下

@ComponentScan({"com.xxx","config"})
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")

public class SpringConfiguration {

}

jdbcConfig類中是數據庫相關配置類,用於取代Spring原xml配置文件中配置的數據庫相關內容

其中 @Scope("prototype")代表多例。

@Value註解用於將我們的jdbcConfig.properties配置文件的值讀取出來

@Qualifier註解用於當我們有兩個dataSource對象,該註解可指定我們具體使用的是哪個。

public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    //用於創建一個QueryRunner對象
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    //創建數據源對象
    @Bean(name = "ds2")
    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);
        }
    }

    @Bean(name = "ds1")
    public DataSource createDataSource1() {
        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.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/xxxx
jdbc.username=root
jdbc.password=root

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章