应用上下文配置【AppConfig】
从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();
- }
应用上下文配置【AppConfig】的更多相关文章
- SpringMVC4零配置--Web上下文配置【MvcConfig】
与SpringSecurity的配置类似,spring同样为我们提供了一个实现类WebMvcConfigurationSupport和一个注解@EnableWebMvc以帮助我们减少bean的声明. ...
- OsharpNS轻量级.net core快速开发框架简明入门教程-多上下文配置(多个数据库的使用)
OsharpNS轻量级.net core快速开发框架简明入门教程 教程目录 从零开始启动Osharp 1.1. 使用OsharpNS项目模板创建项目 1.2. 配置数据库连接串并启动项目 1.3. O ...
- Web上下文配置【MvcConfig】
基于Servlet3.0规范和SpringMVC4注解式配置方式,实现零xml配置,弄了个小demo,供交流讨论. 项目说明如下: 1.db.sql是项目中用到的表,数据库使用的是oracle11g ...
- Jetty:配置上下文
这篇文件讲述配置Jetty上下文的各种选项. 设置上下文路径 上下文路径是一个URL路径的前缀,用于将一个输入请求相应到相应的上下文.Java Servlet Server的URL通常的格式为:htt ...
- spring的父子上下文容器及配置
本文由作者张远道授权网易云社区发布. spring父子容器 spring总的上下文容器有父子之分.父容器和子容器.父容器对子容器可见,子容器对父容器不可见. 对于传统的spring mvc来说,spr ...
- SpringMVC4零配置--web.xml
servlet3.0+规范后,允许servlet,filter,listener不必声明在web.xml中,而是以硬编码的方式存在,实现容器的零配置. ServletContainerInitiali ...
- SpringMvc4.2.5 零配置出现 No mapping found for HTTP request with URI(转)
原文地址:SpringMvc4.2.5 零配置出现 No mapping found for HTTP request with URI 采用 spring 零配置,参考 http://hanqunf ...
- 【Java Web开发学习】Spring MVC 开始配置
Spring MVC 开始配置 转载:http://www.cnblogs.com/yangchongxing/p/8871370.htm 学习搭建最简单的Spring MVC框架. ======== ...
- springmvc笔记(基本配置,核心文件,路径,参数,文件上传,json整合)
首先导入jar包 大家注意一下我的springmvc,jackson,common-up的jar包版本.其他版本有可能出现不兼容. src文件: webroot目录: web.xml <?xml ...
随机推荐
- C# SQLiteDataReader获得数据库指定字段的值
获得数据库指定字段的值,赋给本地变量 (1)如下,获得userinfo数据表里的字段"userid"."orgid", string userid=" ...
- Linux 常用
1,解决ssh登录慢的问题记录 vim /etc/ssh/ssh_config # GSSAPIAuthentication no 把下面这一行的注释去掉 2,Linux查看当前是什么系统 ...
- wp8.1 Study11:APP里文件读写和使用XML和Json序列化
一.文件读写 1.基本操作(使用FileIO API) 这个方法在上一个stduy已经学过,那么贴出来复习下,代码如下: private async void writeTextToLocalStor ...
- Android设计画面中有EditText时取消启动时自动获得焦点调用系统输入法的方法
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools= ...
- SQL CAST, CONVERT 比较
本文转自:http://www.cnblogs.com/denylau/archive/2010/12/01/1893371.html if (@StartTime > @EndTime) ...
- Redhat6.x下如何制作虚拟机快照和镜像封装
一.虚拟机快照 1.确认你的物理机上的vg还有足够的剩余空间 [root@hacker ~]# vgs VG #PV #LV #SN Attr VSize VFree vg_ ...
- java.io.IOException: open failed: EACCES (Permission denied)问题解决
1. 问题描述:在Android中,用程序访问Sdcard时,有时出现“java.io.IOException: open failed: EACCES (Permission denied)&qu ...
- TrueType, OpenType, PCL和PostScript字体版本nterleaved 2 of 5 Barcode Font Advantage Package
Interleaved 2 of 5 Barcode Font Advantage Package包含了TrueType, OpenType, PCL和PostScript字体版本. 提供了超过30个 ...
- [转]ps/2键盘线序识别方法
from: http://www.360doc.com/content/11/0816/19/844619_140875056.shtml 经常看到有人询问ps/2线坏了,更换的时候如何测线序连线,或 ...
- [网络技术][转]PPTP连接过程
转自:http://blog.csdn.net/zhu_hit/article/details/5698958 在未来几天会总结一下PPTP的工作过程,分为以下3篇讲述. 1. PPTP连接过程: 2 ...