从spring3.0开始,Spring将JavaConfig整合到核心模块,普通的POJO只需要标注@Configuration注解,就可以成为spring配置类,并通过在方法上标注@Bean注解的方式注入bean。
Xml配置和Java类配置对比如下:
applicationContext-AppConfig.xml
- <!-- 激活自动代理功能 参看:web.function.aop.aspect.DemoAspect -->
- <aop:aspectj-autoproxy proxy-target-class="true" />
- <context:component-scan base-package="web.function">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- <import resource="classpath:config/context/applicationContext-CachingConfig.xml" />
- <import resource="classpath:config/context/applicationContext-DaoConfig.xml" />
AppConfig.java
- @Configuration
- @ComponentScan(basePackages = "web.function", excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = { Controller.class }) })
- @EnableAspectJAutoProxy(proxyTargetClass=true)
- @Import({CachingConfig.class,DaoConfig.class})
- public class AppConfig {
- }
applicationContext-CachingConfig.xml
- <!-- 启用缓存注解 -->
- <cache:annotation-driven cache-manager="cacheManager" />
- <!-- cacheManager工厂类,指定ehcache.xml的位置 -->
- <bean id="cacheManagerFactory"
- class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
- p:configLocation="classpath:/config/ehcache.xml" />
- <!-- 声明cacheManager -->
- <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
- p:cacheManager-ref="cacheManagerFactory" />
CachingConfig.java
- @Configuration
- @EnableCaching//<!-- 启用缓存注解 --> <cache:annotation-driven cache-manager="cacheManager" />
- public class CachingConfig {
- private static final Logger logger = Logger.getLogger(CachingConfig.class);
- @Bean
- public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
- EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
- ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource(
- "config/ehcache.xml"));
- return ehCacheManagerFactoryBean;
- }
- @Bean
- public CacheManager cacheManager() {
- logger.info("EhCacheCacheManager");
- EhCacheCacheManager cacheManager = new EhCacheCacheManager();
- cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
- return cacheManager;
- }
- }
applicationContext-DaoConfig.xml
- <import resource="classpath:config/context/applicationContext-DataSourceConfig.xml" />
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="packagesToScan">
- <list>
- <value>web.function.**.model.oracle</value>
- </list>
- </property>
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">
- ${hibernate.dialect}
- </prop>
- <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
- <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
- </props>
- </property>
- </bean>
- <!-- hibernateDAO -->
- <bean id="hibernateDAO" class="web.dao.hibernate.impl.CP_Hibernate4DAOImpl">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate4.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory" />
- </bean>
- <!-- 启用事务注解功能 -->
- <tx:annotation-driven transaction-manager="transactionManager" />
DaoConfig.java
- @Configuration
- //启用注解事务管理,使用CGLib代理
- @EnableTransactionManagement(proxyTargetClass = true)
- @Import({DataSourceConfig.class})
- public class DaoConfig {
- private static final Logger logger = Logger.getLogger(DaoConfig.class);
- @Value("${hibernate.dialect}")
- String hibernate_dialect;
- @Value("${hibernate.show_sql}")
- String hibernate_show_sql;
- /**
- * 描述 : <负责解析资源文件>. <br>
- *<p>
- <这个类必须有,而且必须声明为static,否则不能正常解析>
- </p>
- * @return
- */
- @Bean
- public static PropertySourcesPlaceholderConfigurer placehodlerConfigurer() {
- logger.info("PropertySourcesPlaceholderConfigurer");
- return new PropertySourcesPlaceholderConfigurer();
- }
- @Resource(name="dataSource")
- public DataSource dataSource;
- @Bean(name = "sessionFactory")
- public LocalSessionFactoryBean localSessionFactoryBean() {
- logger.info("sessionFactory");
- LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
- sessionFactory.setDataSource(dataSource);
- String[] packagesToScan = new String[] { "web.function.**.model.oracle" };
- sessionFactory.setPackagesToScan(packagesToScan);
- Properties hibernateProperties = new Properties();
- hibernateProperties.setProperty("hibernate.dialect", hibernate_dialect);
- hibernateProperties.setProperty("hibernate.show_sql",
- hibernate_show_sql);
- hibernateProperties.setProperty(
- "hibernate.current_session_context_class",
- "org.springframework.orm.hibernate4.SpringSessionContext");
- sessionFactory.setHibernateProperties(hibernateProperties);
- return sessionFactory;
- }
- @Bean(name = "hibernateDAO")
- public CP_Hibernate4DAOImpl hibernate4Dao() {
- logger.info("hibernateDAO");
- CP_Hibernate4DAOImpl dao = new CP_Hibernate4DAOImpl();
- dao.setSessionFactory(localSessionFactoryBean().getObject());
- return dao;
- }
- @Bean(name = "transactionManager")
- public HibernateTransactionManager hibernateTransactionManager() {
- logger.info("transactionManager");
- HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
- hibernateTransactionManager.setSessionFactory(localSessionFactoryBean()
- .getObject());
- return hibernateTransactionManager;
- }
- }
applicationContext-DataSourceConfig.xml
- <context:property-placeholder
- location="classpath:/config/properties/db.properties" />
- <!-- 数据源 -->
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="${jdbc.driver}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- </bean>
DataSourceConfig.java
- @Configuration
- //加载资源文件
- @PropertySource({"classpath:/config/properties/db.properties"})
- public class DataSourceConfig {
- private static final Logger logger = Logger.getLogger(DataSourceConfig.class);
- /*
- * 绑定资源属性
- */
- @Value("${jdbc.driver}")
- String driverClass;
- @Value("${jdbc.url}")
- String url;
- @Value("${jdbc.username}")
- String userName;
- @Value("${jdbc.password}")
- String passWord;
- @Bean(name = "dataSource")
- public DataSource dataSource() {
- logger.info("DataSource");
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName(driverClass);
- dataSource.setUrl(url);
- dataSource.setUsername(userName);
- dataSource.setPassword(passWord);
- return dataSource;
- }
- }
DataSource如果使用JNDI的方式如下:
xml配置:
- <jee:jndi-lookup id="dataSource" jndi-name="jdbc/demoDB" />
Java类配置:
- @Bean
- public JndiObjectFactoryBean jndiObjectFactoryBean(){
- JndiObjectFactoryBean factory = new JndiObjectFactoryBean();
- // factory.setJndiName("java:comp/env/jdbc/demoDB"); //两种方式均可,spring会自动补齐
- factory.setJndiName("jdbc/demoDB");
- return factory;
- }
- @Bean(name = "dataSource")
- public DataSource dataSource() throws Exception{
- logger.info("DataSourceJNDI");
- return (DataSource)jndiObjectFactoryBean().getObject();
- }