当前位置:首页 > 开发 > 开源软件 > 正文

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

发表于: 2015-01-06   作者:conkeyn   来源:转载   浏览:
摘要:     public class ZeusWebApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) { WebApplicationContext rootContext = WebApp

 

 

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;
	//	}

}

 

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

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号