Spring中@Configuration和@Bean用法

1,简介说明
用@Configuration注解的类,等价 与XML中配置beans;    (例如:spring-servlet.xml中的beans)

用@Bean标注方法等价于XML中配置的bean。  (例如:spring-servlet.xml中的bean)


2,Spring中为了减少xml中配置,可以创建一个配置类(例如ExampleConfiguration)来对bean进行配置。
(用代码配置)


例如:原本可以这样
1,配置spring配置文件来启用Java注解

<?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:batch="http://www.springframework.org/schema/batch"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jdbc="http://www.springframework.org/schema/jdbc"
        xsi:schemaLocation="
                http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
                http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                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-3.0.xsd">

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

</beans>

2、定义一个配置类

@Configuration
public class ExampleConfiguration {

        @Value("${batch.jdbc.driver}")
        private String driverClassName;

        @Value("${batch.jdbc.url}")
        private String driverUrl;

        @Value("${batch.jdbc.user}")
        private String driverUsername;

        @Value("${batch.jdbc.password}")
        private String driverPassword;

        @Bean(name = "dataSource")
        public DataSource dataSource() {
                BasicDataSource dataSource = new BasicDataSource();
                dataSource.setDriverClassName(driverClassName);
                dataSource.setUrl(driverUrl);
                dataSource.setUsername(driverUsername);
                dataSource.setPassword(driverPassword);
                return dataSource;
        }

        @Bean
        public PlatformTransactionManager transactionManager() {
                return new DataSourceTransactionManager(dataSource());
        }

}




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

康耶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值