Spring MVC配置
1. xml方式
-
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <!-- needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> <!-- 配置为/*则dispatcherServlet将会拦截.jsp,而配置为/则不会拦截jsp页面 --> <!-- <url-pattern>/*</url-pattern> --> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
-
application-context-config(spring容器配置)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启服务层接口的自动扫描 --> <context:component-scan base-package="org.lwt.service"/> <!-- 引入属性配置文件 --> <!-- <context:property-placeholder location="classpath:data.properties"/> --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 1. 配置数据源,此处使用druid数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/employees?useSSL=false&serverTimezone=UTC&nullCatalogMeansCurrent=true"/> <property name="username" value="root"/> <property name="password" value="123456root"/> <property name="filters" value="stat"/> <property name="maxActive" value="20"/> <property name="initialSize" value="1"/> <property name="maxWait" value="60000"/> <property name="minIdle" value="1"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT 'x'"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> </bean> <!-- 2. 创建SqlSession的工厂 --> <!-- dataSource:引用数据源,统一加载配置--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" ></property> <!-- 自动配置别名-作用类似mybatis-config.xml的别名 --> <property name="typeAliasesPackage" value="org.lwt.entity" /> <!-- 设置别名的类加上父类限定 --> <!-- <property name="typeAliasesSuperType" value="com.demo.common.base.BaseEntity"/> --> <!-- 当mybatis的xml文件和mapper接口不在相同包下时,需要用mapperLocations属性指定xml文件的路径 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <!-- 指定mybatis核心配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 添加分页插件 --> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helperDialect=mysql reasonable=true supportMethodsArguments=true params=count=countSql autoRuntimeDialect=true </value> </property> </bean> </array> </property> </bean> <!-- 3. 自动扫描加载Sql映射文件/接口(此处使用mabatis通用mapper插件,) --> <bean id="mapperScannerConfigurer"class= "tk.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- basePackage:指定sql映射接口所在的包(自动扫描)。 --> <property name="basePackage" value="org.lwt.dao"></property> <!-- 将带有org.apache.ibatis.annotations.Mapper注解的接口作为mybatis 映射文件接口 --> <property name="annotationClass"value= "org.apache.ibatis.annotations.Mapper"/> <property name="properties"> <value> mappers=tk.mybatis.mapper.common.Mapper </value> </property> </bean> <!-- 4. 事务管理 --> <!-- dataSource:引用上面定义的数据源 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 5. 使用声明式事务 --> <!-- transaction-manager:引用上面定义的事务管理器 --> <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <bean id="sqlSession" class= "org.mybatis.spring.SqlSessionTemplate" scope="prototype"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> </beans>
注:application-config.xml中主要配置数据源,数据库事务等全局使用的bean。
-
spring-mvc-config.xml(springMVC容器配置)
<?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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <!--RequestMappingHandlerAdapter--> <mvc:annotation-driven /> <!-- 打开使用注解自动检测功能自动注册Bean,扫描@Controller --> <context:component-scan base-package="org.lwt.controller"> </context:component-scan> <!-- 视图配置 --> <!-- 对转向页面的路径解析,指定输出视图的前后缀,controller返回的视图直接加上此前后缀 --> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/project/" p:suffix=".jsp" /> --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="100000"/> </bean> <!-- 不拦截静态资源文件 --> <!-- <mvc:resources location="/" mapping="/**" /> --> <mvc:default-servlet-handler/> </beans>
注:spring-mvc-config.xml中主要配置试图解析器,controller类扫描包,静态资源处理的springMVC中使用相关的配置。
-
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <plugins> </plugins> </configuration>
注: mybatis-config.xml类主要是mybatis相关的配置。
-
整合通用mapper
在将mybatis-spring原来的org.mybatis.spring.mapper.MapperScannerConfigurer改为tk.mybatis.spring.mapper.MapperScannerConfigurer并作如下的配置即可。
<!-- 3. 自动扫描加载Sql映射文件/接口(此处使用mabatis通用mapper插件,) --> <bean id="mapperScannerConfigurer"class= "tk.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- basePackage:指定sql映射接口所在的包(自动扫描), 由于本项目中使用了通用mapper,需要设置mapper接口所在的包,同时需要在mapper接口类上加上 org.apache.ibatis.annotations.Mapper注解,才能通过bean管理mapper接口。 --> <property name="basePackage" value="org.lwt.dao"></property> <property name="annotationClass"value= "org.apache.ibatis.annotations.Mapper"/> <property name="properties"> <value> mappers=tk.mybatis.mapper.common.Mapper </value> </property> </bean>
-
整合pagehelper分页插件
在sqlsessionFactoryBean中添加如下配置或以在mybatis配置文件中添加插件的方式添加都可以。
<!-- 添加分页插件 --> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helperDialect=mysql reasonable=true supportMethodsArguments=true params=count=countSql autoRuntimeDialect=true </value> </property> </bean> </array> </property>
或在mybatis-config.xml中添加插件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property></property> </plugin> </plugins> </configuration>
-
log4j.properties
log4j.rootLogger=DEBUG, stdout log4j.logger.com.github.pagehelper=DEBUG log4j.logger.org.apache.ibatis=DEBUG log4j.logger.com.github.pagehelper.mapper = TRACE ### Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
-
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.lwt</groupId> <artifactId>shiro-g</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>spring-mvc-shiro-a</artifactId> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 编译jdk版本 --> <jdk.version>1.8</jdk.version> <!-- 依赖版本 --> <mybatis.version>3.4.6</mybatis.version> <mapper.version>4.0.4</mapper.version> <pagehelper.version>5.1.4</pagehelper.version> <mysql.version>6.0.6</mysql.version> <spring.version>4.3.8.RELEASE</spring.version> <mybatis.spring.version>1.3.2</mybatis.spring.version> <jackson.version>2.9.6</jackson.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--web--> <!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> <version>2.1</version> </dependency> --> <!--jsp支持--> <!-- servlet 依赖. --> <!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> tomcat 的支持. <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>9.0.10</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>9.0.10</version> <scope>provided</scope> </dependency> --> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>javax.transaction-api</artifactId> <version>1.3</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- spring json --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!--上传文件--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- Mybatis Generator --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> <scope>compile</scope> <optional>true</optional> </dependency> <!--分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!--通用Mapper--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mapper.version}</version> </dependency> </dependencies> <!-- 中央仓库配置 --> <repositories> <repository> <id>nexus</id> <name>local private nexus</name> <url>http://maven.oschina.net/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>sonatype-nexus-releases</id> <name>Sonatype Nexus Releases</name> <url>http://oss.sonatype.org/content/repositories/releases</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>sonatype-nexus-snapshots</id> <name>Sonatype Nexus Snapshots</name> <url>http://oss.sonatype.org/content/repositories/snapshots</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <build> <!-- <resources> <resource> <directory>${basedir}/src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>${basedir}/src/main/resources</directory> </resource> </resources> --> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <configurationFile>${basedir}/src/main/resources/genereator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mapper.version}</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
2.javaconfig方式
-
dispatcherServlet相关配置类
package org.lwt.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * dipatcherServlet相关配置, 用来代替web.xml中的 * dipatcherServlet和ContextLoadListener相关配置 * @author Administrator * */ public class DispatcherInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] {RootConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] {WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[] {"/"}; } /** * add 为dispatcherServlet注册一个指定的Filter */ @Override protected Filter[] getServletFilters() { return new Filter[] {new MyFilter()}; } }
-
spring 根容器配置类
package org.lwt.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.web.servlet.config.annotation.EnableWebMvc; /** * spring 根容器配置类 * 在此处配置数据源等 * @author Administrator * */ @Configuration // 扫描org.lwt包下的类将其注册为spring的Bean,并且不扫描包含@EnableWebMvc注解的类 @ComponentScan( basePackages={"org.lwt"}, excludeFilters = { @Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)} ) public class RootConfig { }
-
spring mvc容器配置类
package org.lwt.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * springMVC容器配置 * 在此处配置试图解析器等 * * * @author Administrator * */ @Configuration @EnableWebMvc // 启用mvc @ComponentScan("org.lwt.controller") // 扫描指定包下的类将其注册为spring的一个bean public class WebConfig extends WebMvcConfigurerAdapter { //配置静态资源的处理 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { super.configureDefaultServletHandling(configurer); } }
-
添加自定义Servlet、Filter,listener
通过实现WebApplicationInitializer接口并实现onStartup方法,在web容器启动的时候就会加载相关的servlet、Filter和listener。
public class ServletConfig implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { System.out.println("开始添加一个servlet..."); ServletRegistration.Dynamic myServlet = servletContext.addServlet("myServlet", MyServlet.class); myServlet.addMapping("/myservlet/**"); myServlet.setLoadOnStartup(1); FilterRegistration.Dynamic myFilter = servletContext.addFilter("myFilter", MyFilter.class); myFilter.addMappingForUrlPatterns(null, false, "/myservlet/**"); myFilter.addMappingForServletNames(null, false, "myServlet"); myFilter.setInitParameter("exclusions","*.jsp"); } }
-
配置通用mapper
package org.lwt.config; import java.util.ArrayList; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.entity.Config; import tk.mybatis.mapper.mapperhelper.MapperHelper; import tk.mybatis.spring.annotation.MapperScan; /** * m 配置通用mapper * @author Administrator * */ @Configuration @MapperScan( value = "org.lwt.dao", // 指定mapper接口存放的包 mapperHelperRef="mapperHelper", sqlSessionFactoryRef="sqlSessionFactory" ) public class MyBatisConfigRef { @Bean public MapperHelper mapperHelper() { Config config = new Config(); List<Class> mappers = new ArrayList<>(); mappers.add(Mapper.class); config.setMappers(mappers); MapperHelper mapperHelper = new MapperHelper(); mapperHelper.setConfig(config); return mapperHelper; } }
-
整合mybatis(Rootconfig.java)
@Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) { ClassPathResource cpr = new ClassPathResource("/spring/applicationContext.xml"); SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 1.设置数据源 sqlSessionFactoryBean.setDataSource(dataSource); // 2. 设置mapper配置文件的位置, new ClassPathResource("/mapper/*.xml")表示加载类路径下的mapper文件夹下的 .xml文件 sqlSessionFactoryBean.setMapperLocations(new Resource[] {new ClassPathResource("/mapper/DepartmentsMapper.xml")}); // 3. 设置实体类的别名 sqlSessionFactoryBean.setTypeAliasesPackage("org.lwt.entity"); // 4. 添加mybatis pageHelper分页插件 sqlSessionFactoryBean.setPlugins(new Interceptor[] {pageInterceptor()}); return sqlSessionFactoryBean; }
-
添加分页插件Bean(RootConfig.java)
@Bean public PageInterceptor pageInterceptor() { PageInterceptor interceptor = new PageInterceptor(); Properties props = new Properties(); props.setProperty("helperDialect", "mysql"); props.setProperty("reasonable", "true"); props.setProperty("supportMethodsArguments", "mysql"); props.setProperty("autoRuntimeDialect", "true"); interceptor.setProperties(props); return interceptor; }
-
数据源
@Bean public DataSource druidDataSource(PropertiesConfig propertyConfigurer) { /*System.out.println("数据库用户名>>: "+propertyConfigurer.getProperty("username")); System.out.println("数据库用户密码>>: "+propertyConfigurer.getProperty("spring.datasource.password"));*/ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(propertyConfigurer.getProperty("spring.datasource.driverClassName")); dataSource.setUrl(propertyConfigurer.getProperty("spring.datasource.url")); dataSource.setUsername(propertyConfigurer.getProperty("spring.datasource.username")); dataSource.setPassword(propertyConfigurer.getProperty("spring.datasource.password")); return dataSource; }
3. 读取properties文件
-
@Value注解方式读取
-
创建PropertiesFactoryBean,
@Bean public PropertiesFactoryBean prop() { String path = getClass().getClassLoader().getResource("dataSource.properties").getPath(); path = path.substring(1, path.length()); System.out.println("资源路径:"+path); PropertiesFactoryBean props = new PropertiesFactoryBean(); Resource resource; try { resource = new InputStreamResource(new FileInputStream(new File(path))); props.setLocation(resource); } catch (FileNotFoundException e) { e.printStackTrace(); } return props; }
-
在配置读取到属性中
@Value("#{prop.username}") private String username; @Value("#{props.password}") private String password;
注: 使用这种方式时,properties文件的属性名不能有'.',即不能是spring.datasource.password,否则会报错误:
EL1008E: Property or field 'spring' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
-
-
将properties文件中的属性值读取到一个类中使用
-
创建保存属性文件键值对的类,该类继承PropertyPlaceholderConfigurer
/** * pro保存属性文件中的键值对的类 * @author Administrator * */ public class PropertiesConfig extends PropertyPlaceholderConfigurer { private Properties props; @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); this.props = props; } @Override public void setIgnoreUnresolvablePlaceholders(boolean ignoreUnresolvablePlaceholders) { super.setIgnoreUnresolvablePlaceholders(ignoreUnresolvablePlaceholders); } @Override public void setLocation(Resource location) { super.setLocation(location); } @Override public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound) { super.setIgnoreResourceNotFound(ignoreResourceNotFound); } public String getProperty(String key) { return this.props.getProperty(key); } public String getProperty(String key, String defaultValue) { return this.props.getProperty(key, defaultValue); } public Object setProperty(String key, String value) { return this.props.setProperty(key, value); } }
-
创建一个该类的bean,配置属性文件的位置
/** * props 创建一个Bean,用来存储指定属性文件的键值对 * @return */ @Bean public PropertiesConfig propertyConfigurer() { String path = getClass().getClassLoader().getResource("dataSource.properties").getPath(); path = path.substring(1, path.length()); PropertiesConfig config = new PropertiesConfig(); config.setIgnoreResourceNotFound(true); config.setIgnoreUnresolvablePlaceholders(true); try { config.setLocation(new InputStreamResource(new FileInputStream(new File(path)))); } catch (FileNotFoundException e) { e.printStackTrace(); } return config; }
-
在要使用properties文件的键值对的类中注入PropertiesConfig,之后即可获取属性文件的属性值
@AutoWired private PropertiesConfig propertyConfigurer; String username = propertyConfigurer.getProperty("spring.datasource.username");
-
-
properties文件示例:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost:3306/employees?useSSL=false&serverTimezone=UTC&nullCatalogMeansCurrent=true spring.datasource.username=root spring.datasource.password= spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=30000 spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 spring.datasource.filters=stat,wall,log4j spring.datasource.validationQuery=SELECT1FROMDUAL spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000