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;