应用上下文配置【AppConfig】

时间:2023-03-10 02:22:20
应用上下文配置【AppConfig】

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

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

applicationContext-AppConfig.xml

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

 AppConfig.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

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

CachingConfig.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. @Bean
  6. public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
  7. EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
  8. ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource(
  9. "config/ehcache.xml"));
  10. return ehCacheManagerFactoryBean;
  11. }
  12. @Bean
  13. public CacheManager cacheManager() {
  14. logger.info("EhCacheCacheManager");
  15. EhCacheCacheManager cacheManager = new EhCacheCacheManager();
  16. cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
  17. return cacheManager;
  18. }
  19. }

applicationContext-DaoConfig.xml

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

DaoConfig.java

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

applicationContext-DataSourceConfig.xml

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

DataSourceConfig.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. @Bean(name = "dataSource")
  18. public DataSource dataSource() {
  19. logger.info("DataSource");
  20. DriverManagerDataSource dataSource = new DriverManagerDataSource();
  21. dataSource.setDriverClassName(driverClass);
  22. dataSource.setUrl(url);
  23. dataSource.setUsername(userName);
  24. dataSource.setPassword(passWord);
  25. return dataSource;
  26. }
  27. }

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

xml配置:

  1. <jee:jndi-lookup id="dataSource" jndi-name="jdbc/demoDB" />

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. @Bean(name = "dataSource")
  9. public DataSource dataSource() throws Exception{
  10. logger.info("DataSourceJNDI");
  11. return (DataSource)jndiObjectFactoryBean().getObject();
  12. }