`
conkeyn
  • 浏览: 1529671 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

spring 4.x源码方式配置spring beans

 
阅读更多

 

 

public class ZeusWebApplicationInitializer implements WebApplicationInitializer
{

	public void onStartup(ServletContext container)
	{
		WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(container);
		if (rootContext == null)
		{
			rootContext = new AnnotationConfigWebApplicationContext();
			//((AnnotationConfigWebApplicationContext) rootContext).register(DefaultAppConfig.class);
		}
		if (container.getInitParameter("contextConfigLocation") == null)
		{
			container.setInitParameter("contextConfigLocation", "classpath:config/applicationContext.xml");
		}
		ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);
		container.addListener(contextLoaderListener);

		//开启页面会话
		if (container.getFilterRegistration("SpringOpenEntityManagerInViewFilter") == null)
		{
			Filter springOpenEntityManagerInViewFilter = new OpenEntityManagerInViewFilter();
			FilterRegistration springOpenEntityManagerInViewFilterRegistration = container.addFilter("SpringOpenEntityManagerInViewFilter", springOpenEntityManagerInViewFilter);
			springOpenEntityManagerInViewFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC), false, "*.do");
		}

		//web调度器
		if (container.getServletRegistration("dispatcher") == null)
		{
			DispatcherServlet dispatcherServlet = new DispatcherServlet();
			ServletRegistration.Dynamic registration = container.addServlet("dispatcher", dispatcherServlet);
			registration.setLoadOnStartup(1);
			registration.setInitParameter("contextConfigLocation", "classpath:config/dispatcher-servlet.xml");
			registration.addMapping("*.do");
		}
		//字符编码
		if (container.getFilterRegistration("characterEncodingFilter") == null)
		{
			CharacterEncodingFilter def = new CharacterEncodingFilter();
			def.setEncoding("UTF-8");
			FilterRegistration.Dynamic defFilter = container.addFilter("characterEncodingFilter", def);
			defFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC), false, "*.do");
		}

	}
}

 

@Configuration
@ComponentScan(basePackages = {"com.zk.zeus"})
@EnableTransactionManagement
@PropertySource(value = {"classpath:config/hibernate.properties"})
public class BeansConfig extends WebMvcConfigurerAdapter
{
	@Autowired
	private Environment environment;

	private Properties hibernateProperties()
	{
		Properties properties = new Properties();
		properties.put("hibernate.jdbc.batch_size", environment.getRequiredProperty("hibernate.jdbc.batch_size"));
		properties.put("hibernate.jdbc.fetch_size", environment.getRequiredProperty("hibernate.jdbc.fetch_size"));
		properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
		properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
		properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
		properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
		properties.put("hibernate.cache.use_second_level_cache", environment.getRequiredProperty("hibernate.cache.use_second_level_cache"));
		//3.6及以下用provider_class
		//properties.put("hibernate.cache.provider_class", environment.getRequiredProperty("hibernate.cache.provider_class"));
		//4.x用factory_class
		properties.put("hibernate.cache.region.factory_class", environment.getRequiredProperty("hibernate.cache.region.factory_class"));
		properties.put("hibernate.cache.use_structured_entries", environment.getRequiredProperty("hibernate.cache.use_structured_entries"));
		properties.put("hibernate.cache.provider_configuration_file_resource_path", environment.getRequiredProperty("hibernate.cache.provider_configuration_file_resource_path"));
		return properties;
	}

	@Bean
	public LocalSessionFactoryBean sessionFactory()
	{
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());
		sessionFactory.setPackagesToScan(new String[] {"com.zk.zeus.**"});
		sessionFactory.setHibernateProperties(hibernateProperties());
		return sessionFactory;
	}

	@Bean
	public DataSource dataSource()
	{
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(environment.getRequiredProperty("hibernate.connection.driver_class"));
		dataSource.setUrl(environment.getRequiredProperty("hibernate.connection.url"));
		dataSource.setUsername(environment.getRequiredProperty("hibernate.connection.username"));
		dataSource.setPassword(environment.getRequiredProperty("hibernate.connection.password"));
		return dataSource;
	}

	@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(SessionFactory s)
	{
		HibernateTransactionManager txManager = new HibernateTransactionManager();
		txManager.setSessionFactory(s);
		return txManager;
	}
}

 

测试时需要模拟一个web context

//mock a ServletContext
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {BeansConfig1.class})
public class AppConfigTest
{

	@Autowired WebApplicationContext wac; // cached

    @Autowired MockServletContext servletContext; // cached

    @Autowired MockHttpSession session;

    @Autowired MockHttpServletRequest request;

    @Autowired MockHttpServletResponse response;

    @Autowired ServletWebRequest webRequest;
    
	@Resource(name = "employeeService")
	EmployeeService service;

	@Test
	public void testSaveEmployee()
	{
		//AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

		//EmployeeService service = (EmployeeService) context.getBean("employeeService");

		/*
		 * Create Employee1
		 */
		Employee employee1 = new Employee();
		employee1.setName("Han Yenn");
		//employee1.setDate(new Date(2010, 10, 10));
		employee1.setSalary(new BigDecimal(10000));
		employee1.setSsn("ssn00000001");

		/*
		 * Create Employee2
		 */
		Employee employee2 = new Employee();
		employee2.setName("Dan Thomas");
		//employee2.setJoiningDate(new LocalDate(2012, 11, 11));
		employee2.setSalary(new BigDecimal(20000));
		employee2.setSsn("ssn00000002");

		/*
		 * Persist both Employees
		 */
		service.saveEmployee(employee1);
		service.saveEmployee(employee2);

		/*
		 * Get all employees list from database
		 */
		List<Employee> employees = service.findAllEmployees();
		for (Employee emp : employees)
		{
			System.out.println(emp);
		}

		/*
		 * delete an employee
		 */
		service.deleteEmployeeBySsn("ssn00000002");

		/*
		 * update an employee
		 */

		Employee employee = service.findBySsn("ssn00000001");
		employee.setSalary(new BigDecimal(50000));
		service.updateEmployee(employee);

		/*
		 * Get all employees list from database
		 */
		List<Employee> employeeList = service.findAllEmployees();
		for (Employee emp : employeeList)
		{
			System.out.println(emp);
		}

		//	context.close();
	}

}

 

@Configuration
@ComponentScan(basePackages={"com.websystique.spring"})
@EnableTransactionManagement
@Import({BeansConfig.class,WebConfig.class})
public class BeansConfig1 extends WebMvcConfigurerAdapter
{

}

 

import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager;
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource;

@Configuration
@ComponentScan(basePackages = {"com.zk.zeus"})
@EnableTransactionManagement
public class ZeusProfileBeansConfig
{
	@Autowired
	private Environment environment;

	@Bean
	public PersistenceAnnotationBeanPostProcessor pab()
	{
		return new PersistenceAnnotationBeanPostProcessor();
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory()
	{
		LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
		emfb.setPersistenceUnitName("zeus-profile-cassandra");
		emfb.setPersistenceUnitManager(persistenceUnitManager());
		emfb.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
		emfb.setPackagesToScan("com.zk.zeus");
		return emfb;
	}

	@Bean
	public DefaultPersistenceUnitManager persistenceUnitManager()
	{
		DefaultPersistenceUnitManager pum = new DefaultPersistenceUnitManager();
		pum.setPersistenceXmlLocations("META-INF/persistence.xml");

		/*
		 * Map<String, String> propertyMap = new HashMap<String, String>();
		 * propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);
		 * EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, propertyMap);
		 * EntityManager entityManager = emf.createEntityManager();
		 */

		return pum;
	}

	public MatchAlwaysTransactionAttributeSource matchAllWithPropReq()
	{
		MatchAlwaysTransactionAttributeSource matchResource = new MatchAlwaysTransactionAttributeSource();
		//matchResource.setTransactionAttribute(TransactionAttribute.PROPAGATION_REQUIRED);
		return matchResource;
	}

	@Bean
	@Autowired
	public JpaTransactionManager txManager(EntityManagerFactory emf)
	{
		JpaTransactionManager txManager = new JpaTransactionManager();
		txManager.setEntityManagerFactory(emf);
		return txManager;
	}

	//	public JndiTemplate jndiTemplate()
	//	{
	//		JndiTemplate JndiTemplate = new JndiTemplate();
	//		Properties properties = new Properties();
	//		properties.setProperty("java.naming.factory.initial", "org.apache.naming.java.javaURLContextFactory");
	//		properties.setProperty("java.naming.factory.url.pkgs", "org.apache.naming");
	//		return JndiTemplate;
	//	}

}

 

分享到:
评论

相关推荐

    spring3.x源码

    在Spring 3.x中,`org`目录下可能包含了Spring框架的核心模块,如`beans`、`context`、`core`、`aop`等。每个模块都包含了一系列的类和接口,例如`BeanFactory`是所有bean工厂的顶级接口,`ApplicationContext`扩展...

    第一次搭建spring3.x需要的jar和搭建源码

    3. **配置Spring**:创建`beans.xml`或类似配置文件,声明bean及其依赖关系。 4. **编写业务逻辑**:定义Java类作为Spring的bean,利用注解或XML配置进行依赖注入。 5. **创建Spring启动类**:如果开发Web应用,创建...

    org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

    `org.springframework.beans.factory.config.PropertyPlaceholderConfigurer` 是Spring框架中的一个重要组件,主要负责处理配置文件中的占位符替换。这个类是Spring在初始化bean时用来解析和注入环境变量或系统属性...

    spring5.2.5.release编译后的源码.zip

    4. **Spring Boot**:虽然Spring Boot的源码不在此次提供的压缩包中,但Spring 5.2.5.RELEASE与Spring Boot有紧密的集成。Spring Boot简化了Spring应用的配置,通过`@SpringBootApplication`注解就可以快速启动一个...

    spring1.x使用AOP实例

    http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"&gt; &lt;!-- 其他bean定义 --&gt; &lt;!-- ...

    测试spring中的org.springframework.beans.factory.InitializingBean

    在Spring框架中,`org.springframework.beans.factory.InitializingBean`接口是一个非常重要的概念,它用于标记那些需要在初始化完成后执行特定逻辑的bean。这个接口只包含一个方法:`afterPropertiesSet()`,当bean...

    spring3.0.0相关jar包

    org.springframework.beans-3.0.0.RELEASE org.springframework.context.support-3.0.0.RELEASE org.springframework.context-3.0.0.RELEASE org.springframework.core-3.0.0.RELEASE org.springframework....

    官方原版源码 spring-5.2.8.RELEASE.zip

    而`spring-5.2.8.RELEASE-schema.zip`则包含了Spring的XML配置文件的XSD规范,这对于理解Spring的配置方式至关重要。 Spring框架的核心模块包括: 1. **Core Container**(核心容器):这是Spring的基础,包括 ...

    learngit:精通spring4.x源码-源码通

    最后,Spring4.x对配置方式进行了改进,除了传统的XML配置,还引入了基于注解的配置和Java配置。`@Configuration`和`@Component`注解分别用于声明配置类和组件,`@Autowired`实现了依赖注入,这些都是`org.spring...

    spring 3.x source code

    6. **Groovy-based Configuration**:除了XML配置外,Spring 3.x还支持使用Groovy脚本进行配置,提高了配置的简洁性和可读性。 研究Spring 3.x的源代码,我们可以学习到设计模式的应用,如工厂模式、单例模式、代理...

    《spring framework4.3.x源码》

    github下载实在太慢,放一个在这,需要50个字,哇!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!...

    spring源码spring-framework-4.2.5.RELEASE

    深入理解Spring源码需要对Java反射、动态代理、设计模式等有扎实的基础。建议从以下几个步骤入手: 1. 了解基本架构和模块划分。 2. 分析核心类如ApplicationContext、BeanFactory和DispatcherServlet的实现。 3. ...

    spring_MVC源码

    本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,现在这一篇补上。下面开始贴代码。 文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。 先说...

    spring-framework-4.3.17 源码包

    在源码中,`org.springframework.beans.factory` 和 `org.springframework.context` 包下包含了IoC容器的主要实现。 2. AOP:AOP是Spring提供的一种面向切面编程的能力,允许开发者定义“切面”,并在适当的时间...

    spring-beans源码

    《深入剖析Spring Beans源码》 Spring框架是Java开发中不可或缺的部分,其核心组件之一就是`spring-beans`模块。这个模块主要负责Spring容器的创建、管理Bean的生命周期以及依赖注入(Dependency Injection,简称DI...

    spring-framework-5.1.x.zip

    - **Bean工厂**:`org.springframework.beans.factory.BeanFactory`接口及其实现,如`DefaultListableBeanFactory`,负责bean的创建、依赖解析及生命周期管理。 - **AOP代理**:`org.springframework.aop....

    spring.jar包 源码 及说明文档

    《Spring框架4.3.9.RELEASE源码与官方文档详解》 Spring,作为Java领域最流行的开源框架之一,以其强大的功能和灵活的设计理念,深受广大开发者喜爱。本文将围绕"spring.jar包",深入解析Spring 4.3.9.RELEASE版本...

    lz-spring-framework-5.1.x.zip

    《深入剖析Spring Framework 5.1.x:基于IDEA与Gradle的源码构建》 在软件开发领域,Spring Framework是Java平台上的一个基石,它为开发者提供了丰富的功能,包括依赖注入、面向切面编程、数据访问、Web应用支持等...

    spring-spring-framework-4.3.24.RELEASE.zip

    在源码中,`org.springframework.beans.factory.config`包包含了许多关于生命周期的接口和类,如InitializingBean、DisposableBean以及BeanFactoryPostProcessor等。 6. **事件驱动模型**:Spring提供了基于...

Global site tag (gtag.js) - Google Analytics