spring4.0 之 @Configuration注解

@Configuration注解与spring-*.xml达到的目的是一样的。@Configuration是为了完全的取消xml配置文件而改用注解。下面将对其进行对比说明:

beans的加载方式

spring-.xml的加载方式:ClassPathXmlApplicationContext、FileSystemXmlApplicationContext、ContextLoaderListener(用于WEB);
纯注解的加载方式:AnnotationConfigApplicationContext、AnnotationConfigWebApplicationContext(用于WEB);

@Configuration与@Bean

xml配置:

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" 
     default-lazy-init="true" default-autowire="default">

    <bean id="student" class="com.demo.enity.Student" 
                  init-method="init" destroy-method="destroy" lazy-init="false">
        <property name="age" value="18"/>
        <property name="name" value="test"/>
    </bean>

</beans>
public class Student {
    private Integer age;
    private String name;

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        System.out.println("Age : " + age);
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        System.out.println("Name : " + name);
        return name;
    }

    public void printThrowException() {
        System.out.println("Exception raised");
        throw new IllegalArgumentException();
    }

    public void init(){
        System.out.println("=============Student.init==============");
    }

    public void destroy(){
        System.out.println("=============Student.destroy==============");
    }
}
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-bean.xml");
    Student student = context.getBean(Student.class);
    student.getName();
    student.getAge();

注解配置:

@Configuration
@Lazy
//@Profile("test")
public class BeanConfiguration {
    @Bean(name = "student", initMethod = "init", destroyMethod = "destroy")
    @Scope("prototype")
    public Student student(){
        Student student = new Student();
        student.setAge(100);
        student.setName("this is a test name.");
        return student;
    }
}
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(BeanConfiguration.class);
        annotationConfigApplicationContext.refresh();
        Student student1 = annotationConfigApplicationContext.getBean(Student.class);
        student1.getName();
        student1.getAge();

半xml配置半注解:

@Configuration
@Lazy
//@Profile("test")
public class BeanConfiguration {

    @Bean(name = "student", initMethod = "init", destroyMethod = "destroy")
    @Scope("prototype")
    public Student student(){
        Student student = new Student();
        student.setAge(100);
        student.setName("this is a test name.");
        return student;
    }
}
    <bean class="com.demo.configuration.BeanConfiguration"/>
         <context:annotation-config/>
        <!--或者-->
        <context:component-scan base-package="com.demo"/>
    <context:annotation-config/>
       ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-application.xml");
        Student student2 = context.getBean(Student.class);
        student2.getName();
        student2.getAge();
@Configuration与@ComponentScan

xml配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.demo"/>

</beans>
@Component
public class Teacher {
    private Integer age;
    private String name;
    private String id;
        。。。
}
ClassPathXmlApplicationContext context4 = 
new ClassPathXmlApplicationContext("classpath:spring-annotation-componentScan.xml");
Teacher teacher4 = context4.getBean(Teacher.class);
System.out.println("teacher4.hashCode = ["+teacher4.hashCode()+"]");

注解配置:

@Configuration
@ComponentScan("com.demo")
public class ComponentScanConfig {
}
        AnnotationConfigApplicationContext context5 = new AnnotationConfigApplicationContext();
        context5.register(ComponentScanConfig.class);
        context5.refresh();
        Teacher teacher5 = context5.getBean(Teacher.class);
        System.out.println("teacher5.hashCode = ["+teacher5.hashCode()+"]");
@Configuration与@PropertySource

jdbc.properties:

jdbc.url=jdbc:mysql://172.28.1.1:3306/test
jdbc.username=test
jdbc.password=123456
jdbc.driverClassName=com.mysql.jdbc.Driver
druid.initialSize=10
druid.minIdle=5
druid.maxActive=20
druid.maxWait=60000
druid.poolPreparedStatements=true
druid.maxPoolPreparedStatementPerConnectionSize=33
druid.timeBetweenEvictionRunsMillis=60000
druid.minEvictableIdleTimeMillis=300000
druid.validationQuery=select 1 from dual
druid.testWhileIdle=true
druid.testOnBorrow=false
druid.testOnReturn=false
druid.removeAbandoned=true
druid.removeAbandonedTimeout=1800
druid.logAbandoned=true
druid.filters=stat,wall,slf4j
druid.logSlowSql=true
druid.loginUsername=test
druid.loginPassword=123456

xml配置:

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder ignore-unresolvable="true"  location="jdbc.properties" />

    <!-- 配置数据源 使用的是Druid数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"  
        init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${druid.initialSize}" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="${druid.maxActive}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${druid.minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${druid.maxWait}" />
        <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" />
        <!-- 用来检测有效sql -->
        <property name="validationQuery" value="${druid.validationQuery}" />
        <property name="testOnBorrow" value="${druid.testOnBorrow}" />
        <property name="testOnReturn" value="${druid.testOnReturn}" />
        <property name="testWhileIdle" value="${druid.testWhileIdle}" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="${druid.removeAbandoned}" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="${druid.logAbandoned}" />
        <!-- 监控数据库
        <property name="filters" value="${druid.filters}" />
        -->
    </bean>
</beans>                
        ClassPathXmlApplicationContext context6 = 
                new ClassPathXmlApplicationContext("classpath:spring-data.xml");
        DataSource dataSource = context6.getBean(DataSource.class);
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println("url = [" + druidDataSource.getUrl() + "]");
        System.out.println("username = [" + druidDataSource.getUsername() + "]");

注解配置:

@Configuration
@PropertySource("classpath:jdbc.properties")
public class DruidJdbcConfig {
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${druid.initialSize}")
    private int initialSize;
    @Value("${druid.minIdle}")
    private int minIdle;
    @Value("${druid.maxActive}")
    private int maxActive;
    @Value("${druid.maxWait}")
    private int maxWait;
    @Value("${druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    @Value("${druid.validationQuery}")
    private String validationQuery;
    @Value("${druid.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${druid.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${druid.testOnReturn}")
    private boolean testOnReturn;
    @Value("${druid.removeAbandoned}")
    private boolean removeAbandoned;
    @Value("${druid.removeAbandonedTimeout}")
    private int removeAbandonedTimeout;
    @Value("${druid.logAbandoned}")
    private boolean logAbandoned;
    @Value("${druid.filters}")
    private String filters;
    @Value("${druid.logSlowSql}")
    private boolean logSlowSql;
    @Value("${druid.loginUsername}")
    private String loginUsername;
    @Value("${druid.loginPassword}")
    private String loginPassword;

}
        AnnotationConfigApplicationContext context7 = new AnnotationConfigApplicationContext();
        context7.register(DruidJdbcConfig.class);
        context7.refresh();
        DruidJdbcConfig druidJdbcConfig = context7.getBean(DruidJdbcConfig.class);
        System.out.println("url = [" + druidJdbcConfig.getUrl() + "]");
        System.out.println("username = [" + druidJdbcConfig.getUsername() + "]");
@Configuration与@Import

spring-application.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="spring-data.xml" />
</beans>

spring-data.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">

     <context:property-placeholder ignore-unresolvable="true"  location="jdbc.properties" />

     <!-- 配置数据源 使用的是Druid数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
        <property name="url" value="${jdbc.url}" />
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${druid.initialSize}" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="${druid.maxActive}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${druid.minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${druid.maxWait}" />
        <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" />
          <!-- 用来检测有效sql -->
        <property name="validationQuery" value="${druid.validationQuery}" />
        <property name="testOnBorrow" value="${druid.testOnBorrow}" />
        <property name="testOnReturn" value="${druid.testOnReturn}" />
        <property name="testWhileIdle" value="${druid.testWhileIdle}" />
          <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="${druid.removeAbandoned}" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="${druid.logAbandoned}" />
        </bean>
</beans>
        ClassPathXmlApplicationContext context8 = 
                new ClassPathXmlApplicationContext("classpath:spring-application.xml");
        query(context8.getBean(DataSource.class));

注解配置:

@Configuration
@PropertySource("classpath:jdbc.properties")
public class DruidJdbcConfig {
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${druid.initialSize}")
    private int initialSize;
    @Value("${druid.minIdle}")
    private int minIdle;
    @Value("${druid.maxActive}")
    private int maxActive;
    @Value("${druid.maxWait}")
    private int maxWait;
    @Value("${druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    @Value("${druid.validationQuery}")
    private String validationQuery;
    @Value("${druid.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${druid.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${druid.testOnReturn}")
    private boolean testOnReturn;
    @Value("${druid.removeAbandoned}")
    private boolean removeAbandoned;
    @Value("${druid.removeAbandonedTimeout}")
    private int removeAbandonedTimeout;
    @Value("${druid.logAbandoned}")
    private boolean logAbandoned;
    @Value("${druid.filters}")
    private String filters;
    @Value("${druid.logSlowSql}")
    private boolean logSlowSql;
    @Value("${druid.loginUsername}")
    private String loginUsername;
    @Value("${druid.loginPassword}")
    private String loginPassword;

}
@Configuration
@Import(DruidJdbcConfig.class)
public class DruidPoolConfig {
    private final static Logger LOGGER = LoggerFactory.getLogger(DruidPoolConfig.class);
    @Autowired
    private DruidJdbcConfig druidJdbcConfig;

    @Bean
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(druidJdbcConfig.getUrl());
        datasource.setUsername(druidJdbcConfig.getUsername());
        datasource.setPassword(druidJdbcConfig.getPassword());
        datasource.setDriverClassName(druidJdbcConfig.getDriverClassName());
        datasource.setInitialSize(druidJdbcConfig.getInitialSize());
        datasource.setMinIdle(druidJdbcConfig.getMinIdle());
        datasource.setMaxActive(druidJdbcConfig.getMaxActive());
        datasource.setMaxWait(druidJdbcConfig.getMaxWait());
          datasource.setTimeBetweenEvictionRunsMillis(druidJdbcConfig.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(druidJdbcConfig.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(druidJdbcConfig.getValidationQuery());
        datasource.setTestWhileIdle(druidJdbcConfig.isTestWhileIdle());
        datasource.setTestOnBorrow(druidJdbcConfig.isTestOnBorrow());
        datasource.setTestOnReturn(druidJdbcConfig.isTestOnReturn());
        datasource.setRemoveAbandoned(druidJdbcConfig.isRemoveAbandoned());
        datasource.setRemoveAbandonedTimeout(druidJdbcConfig.getRemoveAbandonedTimeout());
        datasource.setLogAbandoned(druidJdbcConfig.isLogAbandoned());
        try {
            datasource.setFilters(druidJdbcConfig.getFilters());
        } catch (SQLException e) {
            LOGGER.error("datasource.setFilters occur error.", e);
        }
        return datasource;
        }
}
        AnnotationConfigApplicationContext context9 = new AnnotationConfigApplicationContext();
        context9.register(DruidPoolConfig.class);
        context9.refresh();
        query(context9.getBean(DataSource.class));
    public static void query(DataSource dataSource) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
                    connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            String sql = "select id,`name`,mobile from t_agent_user where id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 6497);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String mobile = resultSet.getString("mobile");

                System.out.println("id = [" + id + "]");
                System.out.println("name = [" + name + "]");
                System.out.println("mobile = [" + mobile + "]");
            }
            } catch (SQLException e) {
            e.printStackTrace();
            if (connection != null)
                connection.rollback();
        }finally {
            if (connection != null){
                connection.commit();
                connection.setAutoCommit(true);
            }

            if (resultSet != null)
                resultSet.close();
            if (preparedStatement != null)
                preparedStatement.close();
            if (connection != null)
                connection.close();
        }
            }
@Configuration与@ImportResource
@Configuration
@ImportResource("classpath:spring-data.xml")
public class ImportResourceConfig {
}
        AnnotationConfigApplicationContext context10 = new AnnotationConfigApplicationContext();
        context10.register(ImportResourceConfig.class);
        context10.refresh();
        query(context10.getBean(DataSource.class));

参考:https://www.cnblogs.com/duanxz/p/7493276.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原理介绍,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。传统事务中回滚点的使...
今天小编给大家分享的是一文解析spring中事务的传播机制,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区别,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。Spring Cloud Netfli...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。第一步:整合pom文件,在S...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。List 坑列表 = new ArrayList(2);...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓存的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇...
本篇内容主要讲解“Spring中的@Autowired和@Resource注解怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学...
今天小编给大家分享一下SpringSecurity怎么定义多个过滤器链的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家
这篇文章主要介绍“Spring的@Conditional注解怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring的@Con...
这篇文章主要介绍了SpringCloudGateway的熔断限流怎么配置的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringCloud&nb...
今天小编给大家分享一下怎么使用Spring解决循环依赖问题的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考
这篇文章主要介绍“Spring事务及传播机制的原理及应用方法是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Sp...
这篇“SpringCloudAlibaba框架实例应用分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价
本篇内容主要讲解“SpringBoot中怎么使用SpringMVC”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习...
这篇文章主要介绍“SpringMVC适配器模式作用范围是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringMVC
这篇“导入SpringCloud依赖失败如何解决”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家...
这篇文章主要讲解了“SpringMVC核心DispatcherServlet处理流程是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来
今天小编给大家分享一下SpringMVCHttpMessageConverter消息转换器怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以...
这篇文章主要介绍“Spring框架实现依赖注入的原理是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring框架...
本篇内容介绍了“Spring单元测试控制Bean注入的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下