应用上下文配置【AppConfig】

从spring3.0开始,Spring将JavaConfig整合到核心模块,普通的POJO只需要标注@Configuration注解,就可以成为spring配置类,并通过在方法上标注@Bean注解的方式注入bean。

 

Xml配置和Java类配置对比如下:

applicationContext-AppConfig.xml

 

Xml代码  收藏代码
  1. <!-- 激活自动代理功能 参看:web.function.aop.aspect.DemoAspect -->  
  2.     <aop:aspectj-autoproxy proxy-target-class="true" />  
  3.       
  4.     <context:component-scan base-package="web.function">  
  5.         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  6.     </context:component-scan>  
  7.       
  8.       
  9.     <import resource="classpath:config/context/applicationContext-CachingConfig.xml" />  
  10.     <import resource="classpath:config/context/applicationContext-DaoConfig.xml" />  

 AppConfig.java

Java代码  收藏代码
  1. @Configuration  
  2. @ComponentScan(basePackages = "web.function", excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = { Controller.class }) })  
  3. @EnableAspectJAutoProxy(proxyTargetClass=true)  
  4. @Import({CachingConfig.class,DaoConfig.class})  
  5. public class AppConfig {  
  6. }  

 

 

applicationContext-CachingConfig.xml

 

 

Xml代码  收藏代码
  1. <!-- 启用缓存注解 -->  
  2. <cache:annotation-driven cache-manager="cacheManager" />  
  3.   
  4. <!-- cacheManager工厂类,指定ehcache.xml的位置 -->  
  5. <bean id="cacheManagerFactory"  
  6.     class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"  
  7.     p:configLocation="classpath:/config/ehcache.xml" />  
  8.   
  9. <!-- 声明cacheManager -->  
  10. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"  
  11.     p:cacheManager-ref="cacheManagerFactory" />  

CachingConfig.java 

Java代码  收藏代码
  1. @Configuration  
  2. @EnableCaching//<!-- 启用缓存注解 --> <cache:annotation-driven cache-manager="cacheManager" />  
  3. public class CachingConfig {  
  4.     private static final Logger logger = Logger.getLogger(CachingConfig.class);  
  5.   
  6.   
  7.     @Bean  
  8.     public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {  
  9.         EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();  
  10.         ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource(  
  11.                 "config/ehcache.xml"));  
  12.         return ehCacheManagerFactoryBean;  
  13.     }  
  14.   
  15.     @Bean  
  16.     public CacheManager cacheManager() {  
  17.         logger.info("EhCacheCacheManager");  
  18.         EhCacheCacheManager cacheManager = new EhCacheCacheManager();  
  19.         cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());  
  20.         return cacheManager;  
  21.     }  
  22. }  

applicationContext-DaoConfig.xml

 

 

Xml代码  收藏代码
  1. <import resource="classpath:config/context/applicationContext-DataSourceConfig.xml" />  
  2.   
  3.       
  4.     <bean id="sessionFactory"  
  5.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  6.         <property name="dataSource" ref="dataSource" />  
  7.         <property name="packagesToScan">  
  8.             <list>  
  9.                 <value>web.function.**.model.oracle</value>  
  10.             </list>  
  11.         </property>  
  12.         <property name="hibernateProperties">  
  13.             <props>  
  14.                 <prop key="hibernate.dialect">  
  15.                     ${hibernate.dialect}  
  16.                 </prop>  
  17.                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  18.                 <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>  
  19.             </props>  
  20.         </property>  
  21.     </bean>  
  22.   
  23.       
  24.     <!-- hibernateDAO -->  
  25.     <bean id="hibernateDAO" class="web.dao.hibernate.impl.CP_Hibernate4DAOImpl">  
  26.       <property name="sessionFactory" ref="sessionFactory"></property>  
  27.     </bean>  
  28.       
  29.       
  30.       
  31.       
  32.     <bean id="transactionManager"  
  33.         class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  34.         <property name="sessionFactory" ref="sessionFactory" />  
  35.     </bean>  
  36.       
  37.     <!-- 启用事务注解功能 -->  
  38.     <tx:annotation-driven transaction-manager="transactionManager" />  

DaoConfig.java

Java代码  收藏代码
  1. @Configuration  
  2. //启用注解事务管理,使用CGLib代理  
  3. @EnableTransactionManagement(proxyTargetClass = true)  
  4. @Import({DataSourceConfig.class})  
  5. public class DaoConfig {  
  6.   
  7.     private static final Logger logger = Logger.getLogger(DaoConfig.class);  
  8.   
  9.       
  10.     @Value("${hibernate.dialect}")  
  11.     String hibernate_dialect;  
  12.     @Value("${hibernate.show_sql}")  
  13.     String hibernate_show_sql;  
  14.       
  15.     /**                                                           
  16.     * 描述 : <负责解析资源文件>. <br>  
  17.     *<p>  
  18.         <这个类必须有,而且必须声明为static,否则不能正常解析>   
  19.      </p>                                                                                                                                                                                                                                                 
  20.     * @return                                                                                                       
  21.     */    
  22.     @Bean  
  23.     public static PropertySourcesPlaceholderConfigurer placehodlerConfigurer() {  
  24.         logger.info("PropertySourcesPlaceholderConfigurer");  
  25.         return new PropertySourcesPlaceholderConfigurer();  
  26.     }  
  27.       
  28.     @Resource(name="dataSource")  
  29.     public DataSource dataSource;  
  30.   
  31.       
  32.   
  33.     @Bean(name = "sessionFactory")  
  34.     public LocalSessionFactoryBean localSessionFactoryBean() {  
  35.         logger.info("sessionFactory");  
  36.         LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();  
  37.         sessionFactory.setDataSource(dataSource);  
  38.         String[] packagesToScan = new String[] { "web.function.**.model.oracle" };  
  39.         sessionFactory.setPackagesToScan(packagesToScan);  
  40.   
  41.         Properties hibernateProperties = new Properties();  
  42.         hibernateProperties.setProperty("hibernate.dialect", hibernate_dialect);  
  43.         hibernateProperties.setProperty("hibernate.show_sql",  
  44.                 hibernate_show_sql);  
  45.         hibernateProperties.setProperty(  
  46.                 "hibernate.current_session_context_class",  
  47.                 "org.springframework.orm.hibernate4.SpringSessionContext");  
  48.         sessionFactory.setHibernateProperties(hibernateProperties);  
  49.   
  50.         return sessionFactory;  
  51.   
  52.     }  
  53.   
  54.     @Bean(name = "hibernateDAO")  
  55.     public CP_Hibernate4DAOImpl hibernate4Dao() {  
  56.         logger.info("hibernateDAO");  
  57.         CP_Hibernate4DAOImpl dao = new CP_Hibernate4DAOImpl();  
  58.         dao.setSessionFactory(localSessionFactoryBean().getObject());  
  59.         return dao;  
  60.     }  
  61.   
  62.     @Bean(name = "transactionManager")  
  63.     public HibernateTransactionManager hibernateTransactionManager() {  
  64.         logger.info("transactionManager");  
  65.         HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();  
  66.         hibernateTransactionManager.setSessionFactory(localSessionFactoryBean()  
  67.                 .getObject());  
  68.         return hibernateTransactionManager;  
  69.     }  
  70. }  

 

 

applicationContext-DataSourceConfig.xml

Xml代码  收藏代码
  1. <context:property-placeholder  
  2.         location="classpath:/config/properties/db.properties" />  
  3.   
  4.     <!-- 数据源 -->  
  5.     <bean id="dataSource"  
  6.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  7.         <property name="driverClassName" value="${jdbc.driver}" />  
  8.         <property name="url" value="${jdbc.url}" />  
  9.         <property name="username" value="${jdbc.username}" />  
  10.         <property name="password" value="${jdbc.password}" />  
  11.     </bean>  

 

DataSourceConfig.java

Java代码  收藏代码
  1. @Configuration  
  2. //加载资源文件  
  3. @PropertySource({"classpath:/config/properties/db.properties"})  
  4. public class DataSourceConfig {  
  5.     private static final Logger logger = Logger.getLogger(DataSourceConfig.class);  
  6.     /* 
  7.      * 绑定资源属性 
  8.      */  
  9.     @Value("${jdbc.driver}")  
  10.     String driverClass;  
  11.     @Value("${jdbc.url}")  
  12.     String url;  
  13.     @Value("${jdbc.username}")  
  14.     String userName;  
  15.     @Value("${jdbc.password}")  
  16.     String passWord;  
  17.       
  18.     @Bean(name = "dataSource")  
  19.     public DataSource dataSource() {  
  20.         logger.info("DataSource");  
  21.         DriverManagerDataSource dataSource = new DriverManagerDataSource();  
  22.         dataSource.setDriverClassName(driverClass);  
  23.         dataSource.setUrl(url);  
  24.         dataSource.setUsername(userName);  
  25.         dataSource.setPassword(passWord);  
  26.         return dataSource;  
  27.     }  
  28. }  

 

DataSource如果使用JNDI的方式如下:

xml配置:

Xml代码  收藏代码
  1. <jee:jndi-lookup id="dataSource" jndi-name="jdbc/demoDB" />  

Java类配置:

Java代码  收藏代码
  1. @Bean  
  2.     public JndiObjectFactoryBean jndiObjectFactoryBean(){  
  3.         JndiObjectFactoryBean factory = new JndiObjectFactoryBean();  
  4.     //  factory.setJndiName("java:comp/env/jdbc/demoDB"); //两种方式均可,spring会自动补齐  
  5.                 factory.setJndiName("jdbc/demoDB");  
  6.         return factory;  
  7.     }  
  8.       
  9.     @Bean(name = "dataSource")  
  10.     public DataSource dataSource() throws Exception{  
  11.         logger.info("DataSourceJNDI");  
  12.         return (DataSource)jndiObjectFactoryBean().getObject();  
  13.           
  14.     }  

 

posted @ 2016-08-12 14:02  Study_Work  阅读(1906)  评论(0编辑  收藏  举报