@Configuration @Bean

        xml文件里的配置
 <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

        annotation配置

@Configuration    
public class ExampleConfiguration {    
    
    @Value("com.mysql.jdbc.Driver")    
    private String driverClassName;    
    
    @Value("jdbc://xxxx.xx.xxx/xx")    
    private String driverUrl;    
    
    @Value("${root}")    
    private String driverUsername;    
    
    @Value("123456")    
    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());    
    }    
    
}

        @Configuration用于类上,等价于xml中的<beans>,@Bean用于方法上,等价于<bean>,<bean>中的class即要实例化的对象,对应java代码中为return dataSource。

        @Bean要求spring在启动项目时生成一个bean对象(常作为属性对象),方便以后调用。本质上来说和@Service一样都是建立了一个bean对象,都可以用@Autowired调用,但@Bean更颗粒化,比如上面的例子创建dataSource的bean对象显然用@Service的方法不好创建

        接下来可以在其他类中直接调用bean对象

@Autowired
DataSource datasource;

    







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值