spring
一、spring配置类的注解(作用替代主xml的内容)
@Configuration :
作用:用于指定当前类是一个配置类
使用位置:当前类之前
例:@Configuration
public class springConfiguration {
}
@ComponentScan
作用:用于通过注解指定spring在创建容器时要扫描的包(即扫描这些包下的使用了创建类对象进入springIoc的核心容器中的类。)
属性:value、basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
(相当于在主xml中配置了
< ! -- 修改的地方:告知spring在创建容器时要扫描的包-- >
< context: component- scan base- package = "com.fjut" > < / context: component- scan> )
使用位置:当前类之前。
例:@Configuration
@ComponentScan ( "com.fjut" )
@Bean
作用:用于把当前作为bean对象存入spring的ioc的容器中。
属性:
name:用于存入核心容器中后指定bean的id。
(相当于在主xml中配置了
< ! -- 配置jdbcTmplate-- >
< bean id= "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate" scope= "prototype" >
< ! -- 注入数据源(连接池)-- >
< property name= "dataSource" ref= "dataSource" > < / property>
< / bean> )
使用位置:方法之前。
例:
@Bean ( name = "jdbcTemplate" )
@Scope ( "prototype" )
public JdbcTemplate createJdbcTemplate ( DataSource dataSource) {
return new JdbcTemplate ( dataSource) ;
}
细节:若方法有参数,则到核心容器中查找。
例:public JdbcTemplate createJdbcTemplate ( DataSource dataSource)
参数dataSource需要到核心容器中找到对应的类型,若有多个同类型的则找参数名相同的。(也就是和@Autowired 查找方式一样(详细见案例))。
若容器中没有,则参数位置报错。
@Bean ( name = "dataSource" )
public DataSource createDataSource ( ) {
DruidDataSource druidDataSource =