代码方式配置和xml文件方式混合配置spring
来源:互联网 发布:vb select case语句 编辑:程序博客网 时间:2024/04/29 14:46
第一步
@Order(1)public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{ private static final PropertiesLoader propertiesLoader = new PropertiesLoader(); @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[0]; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{MvcConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override protected Filter[] getServletFilters() { return super.getServletFilters(); } @Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext(); Class<?>[] configClasses = getServletConfigClasses(); if (!ObjectUtils.isEmpty(configClasses)) { servletAppContext.register(configClasses); } //读取spring.properties配置文件,这里主要是设置spring的profile Properties prop = propertiesLoader.load("spring.properties"); servletAppContext.getEnvironment().setActiveProfiles(prop.getProperty("spring.profiles.active")); return servletAppContext; }}
其实上一步相当于定义了
* Dispatcher-拦截路径为“/”
* 定义了ApplicationContext
其中 PropertiesLoader 主要在初始化上下文的时候,加载一些配置文件信息
package com.lizo.config.utils;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * Created by hzlizhou on 2016/9/13. */public class PropertiesLoader { public Properties load(String fileName) { Properties prop = new Properties(); InputStream im = null; try { im = findFile(fileName); prop.load(im); } catch (IOException ignore) { } finally { if (im != null) { try { im.close(); } catch (IOException ignore) { } } } return prop; } private InputStream findFile(String fileName) throws FileNotFoundException { InputStream im = findInWorkingDirectory(fileName); if (im == null) im = findInClasspath(fileName); if (im == null) im = findInSourceDirectory(fileName); if (im == null) throw new FileNotFoundException(String.format("File %s not found", fileName)); return im; } private InputStream findInSourceDirectory(String fileName) throws FileNotFoundException { return new FileInputStream("src/main/resources/" + fileName); } private InputStream findInClasspath(String fileName) { return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } private InputStream findInWorkingDirectory(String fileName) { try { return new FileInputStream(System.getProperty("user.dir") + fileName); } catch (FileNotFoundException e) { return null; } }}
第二步 Spring MVC 配置
import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/** * Created by hzlizhou on 2016/9/13. */@Configuration@EnableWebMvc@ComponentScan("com.lizo")public class MvcConfig extends WebMvcConfigurerAdapter { /* @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); } */}
其中 EnableWebMvc 相当于xml配置中
<mvc:annotation-driven/>
也就是自动注册了RequestMappingHandlerMapping, RequestMappingHandlerAdapter 和 ExceptionHandlerExceptionResolver
第三步 配置dataSource
首先使用一个config类,用来加载其他配置文件
@Configuration@PropertySource({"classpath:spring.properties"})@Import(DataSourceConfig.class)@ImportResource("classpath:spring-db.xml")public class AppConfig {}
- @PropertySource——用于加载配置文件
- @Import——加载使用@Configuration注解的配置类
- @ImportResource——加载xml形式的配置文件
@Configuration@PropertySource("classpath:${spring.profiles.active}/jdbc.properties")public class DataSourceConfig { @Value("${jdbcDriver}") String jdbcDriver; @Value("${jdbcUrl}") String jdbcUrl; @Value("${jdbcUser}") String jdbcUser; @Value("${jdbcPassword}") String jdbcPassword; @Bean(name= "dataSource") public DataSource dataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(jdbcDriver); druidDataSource.setUrl(jdbcUrl); druidDataSource.setUsername(jdbcUser); druidDataSource.setPassword(jdbcPassword); return druidDataSource; }}
需要注意的是,上面加载配置文件的路径使用了变量(profile),这样就可以根据不同环境加载不同的配置文件信息
第四步 使用xml配置mybatis
虽然使用代码的配置方式也能配置,这里只是为了说明(其实就和xml配置文件是一样)
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 数据源事物管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- jdbc 模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!-- mybatis 配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations"> <array> <value>classpath*:/**/*mapper.xml</value> </array> </property> </bean> <!-- 扫描mybatis映射接口类 --> <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.lizo.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean></beans>
第五步 单元测试
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = AppConfig.class)public class TestMapperTest { @Autowired TestMapper testMapper; @Test public void test(){ Assert.assertNotNull(testMapper.test()); }}
总结
既然能够兼容两种模式,那么就可以有选择性的选择使用
0 0
- 代码方式配置和xml文件方式混合配置spring
- Spring配置混合方式
- spring-mvc.xml文件的配置方式
- spring中配置Bean的xml方式和注解方式
- spring学习之aop关于xml文件配置和注解方式配置
- Spring基于xml文件的方式配置AOP
- Spring中使用XML文件的方式配置事务
- Spring文件路径配置方式
- spring+hibernate xml和注解方式配置事务
- 4.1 Spring beans的创建和配置(XML方式)
- Android编程方式开发UI界面和XML文件与Java代码混合控制UI界面
- Spring 采用基于XML方式配置事务
- spring配置事务之xml方式
- 配置xml方式实现Spring的aop
- Spring AOP (三) XML配置方式
- Spring 入门 上 (xml 配置方式)
- 十五Spring Aop的xml配置方式
- spring使用xml方式配置属性值
- bzoj 1858: [Scoi2010]序列操作(线段树)
- sql事务及事物
- 接口
- jeecg 里面的三种查询,第一种直接针对数据库查询,自定义查询语法
- Xmanage 登录 ubuntu 16.04
- 代码方式配置和xml文件方式混合配置spring
- win10默认被重置的问题
- Move Zeroes
- 编程程序输出2-1000000之间的所有的完全数
- 模态框的基本显示
- java--json入门
- JSONP
- Android.mk解析
- 浅谈post提交和get提交方式的区别