* New annotations in spring * @Configuration * Role: a configuration class when specifying the current class * Details: When the configuration class is used as a parameter created by the AnnotationConfigApplicationContext object, the annotation can be omitted * @ComponentScan * Function: Used to specify the package that Spring will scan when creating the container through annotations * Attributes: * value: It has the same function as basePackages, both are used to specify the package to be scanned when creating the container * Our use of this annotation is equivalent to configuring in xml: * <context:component-scan base-package="com.itheima"></context:component-scan> * @Bean * Role: used to store the return value of the current method as a bean object in the spring's ioc container * Attributes: * name: used to specify the id of the bean, when not written, the default value is the name of the current method * Details: When we use the annotation configuration method, if the method has parameters, the spring framework will go to the container to find out if there is a bean object that can be used * The search method is the same as Autowired annotations. * @Import * Role: used to import other configuration classes * Attributes: * value: the bytecode used to specify other configuration classes * When we use the Import annotation, the class with Import annotation is the parent configuration class, and the imported is the child configuration class * @PropertySource * Role: used to specify the configuration of the properties file * Attributes: * value: specify the path of the file name * Keyword: classpath means under the class path
@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
@Value("${jdbcDriver}")
private String driver;
@Value("${jdbcUrl}")
private String url;
@Value("${user}")
private String username;
@Value("${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);
}
}
}