SSM整合兩種配置方式——xml和javaConfig,新增分頁外掛pageHelper和通用Mapper
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