当前位置:首页 > 开发 > 编程语言 > Spring > 正文

SpringMVC4零配置--应用上下文配置【AppConfig】

发表于: 2014-09-10   作者:hanqunfeng   来源:转载   浏览:
摘要: 从spring3.0开始,Spring将JavaConfig整合到核心模块,普通的POJO只需要标注@Configuration注解,就可以成为spring配置类,并通过在方法上标注@Bean注解的方式注入bean。   Xml配置和Java类配置对比如下: applicationContext-AppConfig.xml   <!-- 激活自动代理功能 参看:

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

 

SpringMVC4零配置 :代码下载

SpringMVC4零配置--web.xml

SpringMVC4零配置--应用上下文配置【AppConfig】

SpringMVC4零配置--SpringSecurity相关配置【SpringSecurityConfig】

SpringMVC4零配置--Web上下文配置【MvcConfig】

 

 

SpringMVC4零配置--应用上下文配置【AppConfig】

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
随着应用规模的增长服务则需要扩展集群休部署,在集群化部署过程首先要考虑服务负载处理的问题,在
zk+hibernate+spring零配置 zk5.0.5 hibernate3.6 spring3.05 也许你在使用apply或者use一个类名的
我们在以前学习Spring的时候,其所有的配置信息都写在applicationContext.xml里,大致示例如下: ja
我们在以前学习 Spring 的时候,其所有的配置信息都写在 applicationContext.xml 里,大致示例如下
zk+hibernate+spring零配置 zk5.0.5 hibernate3.6 spring3.05 也许你在使用apply或者use一个类名的
文章只是做一个记录,以便日后查阅 本人技术有限,有误的地方请友善指出,谢谢,O(∩_∩)O~ 每次都要
zk+hibernate+spring零配置 zk5.0.5 hibernate3.6 spring3.05 也许你在使用apply或者use一个类名的
zk+hibernate+spring零配置 zk5.0.5 hibernate3.6 spring3.05 也许你在使用apply或者use一个类名的
12.1 概述 12.1.1 什么是零配置 在SSH集成一章中大家注意到项目结构和包结构是不是很有规律,类库放
1.lib 加struts 默认包 ognl-2.6.11.jar struts2-core-2.1.6.jar xwork-2.1.2.jar freemarker-2.3.1
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号