【SpringIOC】Spring配置类代替bean.xml
概述
创建一个配置类,它的作用和bean.xml是一样的
spring中的新注解
@Configuration
作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时(即用xxx.class作为参数且没有其他配置类需要扫描),该注解可以不写
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
@ComponentScan
作用:用于通过注解指定spring在创建容器时要扫描的包
属性:
value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
使用此注解就等同于在xml配置了:<context:component-scan base-package="com.czy"></context:component-scan>
@Bean
作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性:
name:用于指定bean的id。默认值:当前方法的名称
细节:当我们使用注解配置方法时,如果方法有参数,spring框架回去容器中查找有没有可用的bean对象,查找方式和Autowried的方式是一样的(可添加Qualifier指定对象)
@Qualifier
用于指定特定的对象。

@Import
作用:导入其他配置类
属性:
value:指定配置类的字节码。
当我们使用Import注解之后,有Import注解的类就是父配置类,而导入的就是子配置类
@PropertySource
作用:用于指定properties文件的位置(写在配置类上)
属性:
value:指定文件的名称和路径
关键字:classpath,表示类路径(resource文件)下
@PropertySource("classpath:druid.properties")
/**
 * 该类是一个配置类,他的作用与bean.xml相同
 */
@ComponentScan("com.czy")
@Import(JdbcConfig.class)
public class SpringConfiguration {
}
package config;
import com.czy.factory.DruidFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
public class JdbcConfig {
    /**
     * 创建数据源对象
     * @param druidFactory
     * @return
     */
    @Bean("druid")
    public DataSource getDataSource(DruidFactory druidFactory){
        return druidFactory.getDataSource();
    }
    /**
     * 用于创建一个JdbcTemplate对象
     * 不能是单例对象,不然多个线程使用单个template会出现进程问题
     * @param dataSource
     * @return
     */
    @Bean(name = "template")
    @Scope("prototype")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}
案例
原配置文件

配置类代替配置文件
package config;
import com.czy.factory.DruidFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
/**
 * 该类是一个配置类,他的作用与bean.xml相同
 */
@Configuration
@ComponentScan("com.czy")
public class SpringConfiguration {
    /**
     * 创建数据源对象
     * @param druidFactory
     * @return
     */
    @Bean("druid")
    public DataSource getDataSource(DruidFactory druidFactory){
        return druidFactory.getDataSource();
    }
    /**
     * 用于创建一个JdbcTemplate对象
     * 不能是单例对象,不然多个线程使用单个template会出现进程问题
     * @param dataSource
     * @return
     */
    @Bean(name = "template")
    @Scope("prototype")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号