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());
}
}