1. 程式人生 > >spring的純註解的IOC配置

spring的純註解的IOC配置

添加 one data proto hang 數據類型 vax throw chan

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

/**
* 該類是一個配置類,它的作用和bean.xml一樣
* spring中的新註解
* Configuration
* 作用:指定當前類是一個配置類
* 細節:當配置類作為AnnotationConfigApplicationContext對象創建的參數時,該註解可以不寫。
* 註意:主配置類中可以不寫,因為獲取容器時通過ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);掃描主配置類。其余配置類需要寫。並在主配置類中@ComponentScan({"com.zty"})添加掃描的類。
*
* ComponentScan
* 作用:用於通過註解指定spring在創建容器時要掃描的包。
* 屬性:
* value:它和basePackages的作用一樣,都適用於指定創建容器時要掃描的包。
* 我們使用此註解就等同於在xml中配置了:
* <context:component-scan base-package="com.zty"></context:component-scan>
*Bean
* 作用:把當前方法的返回值作為bean對象存入spring的ioc容器中
* 屬性:
* name:用於指定bean的id。默認值是當前方法的名稱
* 細節:
* 當我們使用註解配置方法時,如果方法有參數,spring框架會去容器中查找有沒有可用的bean對象。
* 查找的方式和Autowired註解的作用是一樣的。先根據數據類型查找,再根據id查找。均在ioc容器中查找。
*Import
* 作用:導入其他的配置類.指定配置類的.class
* 屬性:
* value:用於指定配置類的字節碼。
* 當我們使用Import的註解之後,有Import註解的類就是父配置類即主配置類,而導入的都是子配置類
*PropertySource:
* 作用:用於指定properties文件的位置
* 屬性:
* value:指定文件的名稱和路徑。
* 關鍵字:classpath,表示類路徑下
*/
@Configuration
@ComponentScan({"com.zty"})
@Import({})
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
@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對象
* @param dataSource
* @return
*/
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner creatQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}

/**
* 創建數據源對象
* @return
*/
@Bean(name = "dataSourse")
public DataSource creatDataSoure(){
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);
}
}
}

spring的純註解的IOC配置