spring+spring mvc+jpa零配置注解开发
1.spring+spring mvc+jpa零配置使用全注解开发,不在使用xml配置。
工程结构如图:
2.新建maven工程,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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.epudge</groupId>
<artifactId>port</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>port Maven Webapp</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.epudge</groupId>
<artifactId>core-parent</artifactId>
<version>1.0.0</version>
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
<!-- Transaction -->
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
</dependency>
<!-- Zxing -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
</dependency>
<!-- Jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
</dependency>
<!-- Activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</dependency>
<!-- javax.annotation -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
</dependency>
<!-- Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- Commons Fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!-- Commons Codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<!-- Commons Lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- Commons Poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<!-- P6SPY -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
</dependency>
<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Apache Http Client -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- Velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<!-- Sitemesh -->
<dependency>
<groupId>opensymphony</groupId>
<artifactId>sitemesh</artifactId>
</dependency>
<!-- bouncycastle -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.53</version>
</dependency>
<!-- Spring Retry -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<!-- BoneCP -->
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-spring</artifactId>
</dependency>
<!-- Dates -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-hibernate</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-jsptags</artifactId>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</dependency>
<!-- Oracle Driver -->
<dependency>
<groupId>oracle.jdbc.driver</groupId>
<artifactId>ojdbc6</artifactId>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<!-- Spring JPA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>2.0.1.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<artifactId>jdk.tools</artifactId>
<groupId>jdk.tools</groupId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-odm</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<!-- used by Spring MVC Test framework -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- Spring Mobile -->
<dependency>
<groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId>
</dependency>
<!-- JSR 303 with Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<exclusions>
<exclusion>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<scope>runtime</scope>
</dependency>
<!-- CGLIB -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
</dependency>
<!-- Lucene -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>5.5.1</version>
</dependency>
<!-- IK -->
<dependency>
<groupId>org.wltea.ik-analyzer</groupId>
<artifactId>ik-analyzer-solr5</artifactId>
<version>5.x</version>
</dependency>
<!-- Ansj <dependency> <groupId>org.ansj</groupId> <artifactId>ansj_seg</artifactId>
<version>3.7.3</version> </dependency> <dependency> <groupId>org.ansj</groupId>
<artifactId>ansj_lucene5_plug</artifactId> <version>3.7.3</version> </dependency> -->
<!-- <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-core</artifactId>
<version>5.5.1</version> <optional>true</optional> <exclusions> <exclusion>
<groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion>
<exclusion> <artifactId>jdk.tools</artifactId> <groupId>jdk.tools</groupId>
</exclusion> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId>
</exclusion> </exclusions> </dependency> -->
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>5.5.1</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
</dependency>
<!-- Tomcat -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>help</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<argLine>-Xmx512m</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.8.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceExcludes>**/*.js,**/*.css</warSourceExcludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.3</version>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
3.新建类CommonWebInitializer实现接口 WebApplicationInitializer 其对应于web.xml
3.1解析WebApplicationInitializer:
打开接口WebApplicationInitializer我们会发现其实里面什么都没有,这时看SpringServletContainerInitializer会发现他是专门处理WebApplicationInitializer的,实现了接口ServletContainerInitializer ,而在spring中的jar包指定了org.springframework.web.SpringServletContainerInitializer,通过这些,我们也可以自己定义WebApplicationInitializer。
3.2代码:
3.2代码:
package com.epudge.port.config.server;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.FilterRegistration.Dynamic;
import org.jasig.cas.client.session.SingleSignOutHttpSessionListener;
import org.springframework.core.Conventions;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.util.IntrospectorCleanupListener;
/**
*
* @author zenglong
*
* @Description: web.xml配置
*
*/
@Order(1)
public class CommonWebInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
registerServletFilter(servletContext, characterEncodingFilter);
servletContext.addListener(new SingleSignOutHttpSessionListener());
servletContext.addListener(new IntrospectorCleanupListener());
}
/**
* @param servletContext
* @param filter
* @return
*/
protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
String filterName = Conventions.getVariableName(filter);
Dynamic registration = servletContext.addFilter(filterName, filter);
if (registration == null) {
throw new IllegalStateException("Duplicate Filter registration for '" + filterName + "'. Check to ensure the Filter is only configured once.");
}
registration.setAsyncSupported(true);
registration.addMappingForUrlPatterns(getDispatcherTypes(), false, "/*");
return registration;
}
private EnumSet<DispatcherType> getDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC);
}
}
4:SpringMvcInitializer继承抽象类AbstractAnnotationConfigDispatcherServletInitializer MVC相关配置,比如加载spring配置文件,声明DispatcherServlet等
package com.epudge.port.config.server;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.epudge.port.config.SpringRootConfig;
import com.epudge.port.config.SpringWebConfig;
/**
*
* @author zenglong
*
* @Description:mvc相关配置
*
*/
@Order(2)
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
/**
* 应用上下文
*/
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class[] {SpringRootConfig.class};
}
/**
* web上下文
*/
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[] {SpringWebConfig.class};
}
/**
* 指定开始被servlet处理的url,配置从/开始
*/
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
这里最重要的两个方法分别是:getRootConfigClasses(),getServletConfigClasses()
4.2:SpringRootConfig类负责注册除Controller等web层以外的所有bean,包括aop代理,service层,dao层,缓存。
package com.epudge.port.config;
import static com.epudge.port.Constant.BASE_PACKAGES;
import static com.epudge.port.Constant.COMPONENT_SCAN_ASPECTJ;
import static com.epudge.port.Constant.CONFIG_SCAN_ASPECTJ;
import static com.epudge.port.Constant.DAO_SCAN_ASPECTJ;
import static com.epudge.port.Constant.SERVICE_SCAN_ASPECTJ;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.retry.annotation.EnableRetry;
import com.epudge.core.qychat.config.annotation.EnableQyWechat;
/**
*
* @author zenglong
*
* @Description: 负责注册除Controller等web层以外的所有bean,包括aop代理,service层,dao层,缓存
*
*/
@Configuration
@ComponentScan(basePackages = BASE_PACKAGES, useDefaultFilters = false, includeFilters = { @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = { SERVICE_SCAN_ASPECTJ, DAO_SCAN_ASPECTJ, COMPONENT_SCAN_ASPECTJ, CONFIG_SCAN_ASPECTJ }) })
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableRetry
public class SpringRootConfig {
/**
* 国际化
*
* @return
*/
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages/messages", "classpath:org/springframework/security/messages");
return messageSource;
}
}
4.3:SpringWebConfig类:controller相关配置
package com.epudge.port.config;
import static com.epudge.port.Constant.BASE_PACKAGES;
import static com.epudge.port.Constant.CONTROLLER_ADVICE_SCAN_ASPECTJ;
import static com.epudge.port.Constant.CONTROLLER_REST_SCAN_ASPECTJ;
import static com.epudge.port.Constant.CONTROLLER_SCAN_ASPECTJ;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Source;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.BufferedImageHttpMessageConverter;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver;
import org.springframework.mobile.device.DeviceResolverHandlerInterceptor;
import org.springframework.ui.context.ThemeSource;
import org.springframework.ui.context.support.ResourceBundleThemeSource;
import org.springframework.util.ClassUtils;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.theme.CookieThemeResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import com.epudge.core.qychat.callback.converter.QyWechatJaxb2RootElementHttpMessageConverter;
import com.epudge.core.qychat.config.annotation.EnableQyWechatWeb;
import com.epudge.core.remoting.httpinvoke.config.annotation.EnableHttpInvokerService;
import com.epudge.port.config.SpringWebConfig;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* @author zenglong
*
* @Description: controller相关配置
*
*/
@Configuration
@EnableWebMvc
@EnableHttpInvokerService
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackages = BASE_PACKAGES, useDefaultFilters = false, includeFilters = { @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = { CONTROLLER_SCAN_ASPECTJ, CONTROLLER_REST_SCAN_ASPECTJ, CONTROLLER_ADVICE_SCAN_ASPECTJ }) })
public class SpringWebConfig extends WebMvcConfigurerAdapter{
/**
* Jackson2 ObjectMapper
*
* @return
*/
public ObjectMapper objectMapper() {
return Jackson2ObjectMapperBuilder.json().serializationInclusion(JsonInclude.Include.NON_NULL).build().configure(SerializationFeature.INDENT_OUTPUT, true);
}
/**
* 文件上传解析器
*
* @return
*/
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(-1);
return multipartResolver;
}
@Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}
@Bean
public ThemeResolver themeResolver() {
return new CookieThemeResolver();
}
@Bean
public ThemeSource themeSource() {
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
themeSource.setBasenamePrefix("theme.");
return themeSource;
}
/**
* 配置验证器
*/
@Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:validation/messages");
validator.setValidationMessageSource(messageSource);
return validator;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
return new LocaleChangeInterceptor();
}
/**
* 添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(deviceResolverHandlerInterceptor());
registry.addInterceptor(sitePreferenceHandlerInterceptor());
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new ThemeChangeInterceptor());
}*/
/**
* 配置资源处理器
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/apps/**").addResourceLocations("/WEB-INF/pages/");
}
/**
* 是否启用容器默认Servlet处理器
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/**
* 配置试图解析器
*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(jspViewResolver());
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setObjectMapper(objectMapper());
registry.enableContentNegotiation(view);
}
public ViewResolver jspViewResolver() {
InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver();
// jspViewResolver.setCache(false);//解析视图名称是否启用缓存(默认启用)
jspViewResolver.setSuffix(".jsp");
jspViewResolver.setPrefix("/WEB-INF/page/");
jspViewResolver.setRequestContextAttribute("requestContext");
jspViewResolver.setContentType("text/html;charset=UTF-8");
return jspViewResolver;
}
/**
* 配置内容协商解析媒体类型策略
*/
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("action", MediaType.TEXT_HTML);
// 组成ContentNegotiationStrategy解析MediaType.后缀,Map映射,参数format,请求头Accept,默认
configurer.favorPathExtension(true).favorParameter(true).ignoreAcceptHeader(false).defaultContentType(MediaType.TEXT_HTML);
}
}
4.3:我们把一些要扫描的包定义好规则为常量放在Constant类中
package com.epudge.port;
public class Constant {
/**
* Global Serialization value for Spring Security classes.
*
* N.B. Classes are not intended to be serializable between different
* versions. See SEC-1709 for why we still need a serial version.
*/
public static final long SERIAL_VERSION_UID = 400L;
/**
* 代码扫描根包
*/
public static final String BASE_PACKAGES = "com.epudge";
/**
* Spring web 扫描 aspectj
*/
public static final String CONTROLLER_SCAN_ASPECTJ = "@org.springframework.stereotype.Controller com.epudge..*Controller";
public static final String CONTROLLER_REST_SCAN_ASPECTJ = "@org.springframework.web.bind.annotation.RestController com.epudge..*Controller";
public static final String CONTROLLER_ADVICE_SCAN_ASPECTJ = "@org.springframework.web.bind.annotation.ControllerAdvice com.epudge..*ControllerAdvice";
/**
* Spring root 扫描 aspectj
*/
public static final String SERVICE_SCAN_ASPECTJ = "@org.springframework.stereotype.Service (com.epudge..service.impl.*ServiceImpl|| com.epudge..formula.*Service)";
public static final String DAO_SCAN_ASPECTJ = "@org.springframework.stereotype.Repository com.epudge..dao.impl.*DaoImpl";
public static final String COMPONENT_SCAN_ASPECTJ = "@org.springframework.stereotype.Component (com.epudge..*ApplicationListener || com.epudge..*Component || com.epudge..*Endpoint || com.epudge..parser.*Parser)";
public static final String CONFIG_SCAN_ASPECTJ = "@org.springframework.context.annotation.Configuration com.epudge..config.ext.*Config";
/**
* JPA Data 扫描 aspectj
*/
public static final String JPA_REPOSITORY_SCAN_ASPECTJ = "com.epudge..jpa.dao.*Dao && org.springframework.data.repository.Repository+";
/**
* Solr Data 扫描 aspectj
public static final String SOLR_REPOSITORY_SCAN_ASPECTJ = "com.epudge..solr.dao.*Dao && org.springframework.data.repository.Repository+";
*/
/**
* LDAP Data 扫描 aspectj
public static final String LDAP_REPOSITORY_SCAN_ASPECTJ = "com.epudge..ldap.dao.*Dao && org.springframework.data.repository.Repository+";
*/
/**
* 实体扫描根包
*/
public static final String[] ENTITY_PACKAGES_SCAN = { BASE_PACKAGES + ".**.entity" };
/**
* 自定义ID生成器
*/
public static final String ID_GENERATED_NAME = "CodeGenerator";
// public static final String ID_GENERATED_STRATEGY = "com.epudge.help.ext.jpa.code.CodeGenerator";
/**
* 系统配置文件路径
public static final String CONFIG_PROPERTY_SOURCE = "classpath:config.properties";*/
/**
* jdbc配置文件路径
*/
public static final String JDBC_PROPERTY_SOURCE = "classpath:jdbc.properties";
/**
* 单点登录配置文件路径??
public static final String CAS_PROPERTY_SOURCE = "classpath:cas.properties";*/
/**
* activiti配置文件路径
public static final String ENGINE_PROPERTY_SOURCE = "classpath:engine.properties";*/
/**
* ldap配置文件路径
public static final String LDAP_PROPERTY_SOURCE = "classpath:ldap.properties";*/
/**
* solr配置文件路径
public static final String SOLR_PROPERTY_SOURCE = "classpath:solr.properties"; */
/**
* email配置文件路径
public static final String EMAIL_PROPERTY_SOURCE = "classpath:email.properties";*/
}
5.接下来我们配置数据库相关信息,这里用的是jpa,如有不了解的可以先看下我前面的博文。
在oracle中创建表:
CREATE TABLE jpa_persons(
id int(11) PRIMARY KEY ,
age int(11) NOT NULL,
email varchar(255) DEFAULT NULL,
lastName varchar(255) DEFAULT NULL
)
5.1同时我们使用了p6spy:
spy.properties
#################################################################
# P6Spy Options File #
# See documentation for detailed instructions #
# http://p6spy.github.io/p6spy/2.0/configandusage.html #
#################################################################
#################################################################
# MODULES #
# #
# Module list adapts the modular functionality of P6Spy. #
# Only modules listed are active. #
# (default is com.p6spy.engine.logging.P6LogFactory and #
# com.p6spy.engine.spy.P6SpyFactory) #
# Please note that the core module (P6SpyFactory) can't be #
# deactivated. #
# Unlike the other properties, activation of the changes on #
# this one requires reload. #
#################################################################
modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P6LogFactory
################################################################
# CORE (P6SPY) PROPERTIES #
################################################################
# A comma separated list of JDBC drivers to load and register.
# (default is empty)
#
# Note: This is normally only needed when using P6Spy in an
# application server environment with a JNDI data source or when
# using a JDBC driver that does not implement the JDBC 4.0 API
# (specifically automatic registration).
driverlist=oracle.jdbc.OracleDriver
#driverlist=com.MySQL.jdbc.Driver
# for flushing per statement
# (default is false)
#autoflush = false
# sets the date format using Java's SimpleDateFormat routine.
# In case property is not set, miliseconds since 1.1.1970 (unix time) is used (default is empty)
dateformat=yyyy-MM-dd HH:mm:ss
# prints a stack trace for every statement logged
#stacktrace=false
# if stacktrace=true, specifies the stack trace to print
#stacktraceclass=
# determines if property file should be reloaded
# Please note: reload means forgetting all the previously set
# settings (even those set during runtime - via JMX)
# and starting with the clean table
# (default is false)
reloadproperties=false
# determines how often should be reloaded in seconds
# (default is 60)
reloadpropertiesinterval=60
# specifies the appender to use for logging
# Please note: reload means forgetting all the previously set
# settings (even those set during runtime - via JMX)
# and starting with the clean table
# (only the properties read from the configuration file)
# (default is com.p6spy.engine.spy.appender.FileLogger)
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.FileLogger
# name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log)
# (used for com.p6spy.engine.spy.appender.FileLogger only)
# (default is spy.log)
#logfile = spy.log
# append to the p6spy log file. if this is set to false the
# log file is truncated every time. (file logger only)
# (default is true)
append=true
# class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat)
logMessageFormat=com.epudge.port.ext.p6spy.SingleLineFormat
# format that is used for logging of the date/time/... (has to be compatible with java.text.SimpleDateFormat)
# (default is dd-MMM-yy)
#databaseDialectDateFormat=dd-MMM-yy
#################################################################
# DataSource replacement #
# #
# Replace the real DataSource class in your application server #
# configuration with the name com.p6spy.engine.spy.P6DataSource #
# (that provides also connection pooling and xa support). #
# then add the JNDI name and class name of the real #
# DataSource here #
# #
# Values set in this item cannot be reloaded using the #
# reloadproperties variable. Once it is loaded, it remains #
# in memory until the application is restarted. #
# #
#################################################################
#realdatasource=/RealMySqlDS
#realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
#################################################################
# DataSource properties #
# #
# If you are using the DataSource support to intercept calls #
# to a DataSource that requires properties for proper setup, #
# define those properties here. Use name value pairs, separate #
# the name and value with a semicolon, and separate the #
# pairs with commas. #
# #
# The example shown here is for mysql #
# #
#################################################################
#realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar
#################################################################
# JNDI DataSource lookup #
# #
# If you are using the DataSource support outside of an app #
# server, you will probably need to define the JNDI Context #
# environment. #
# #
# If the P6Spy code will be executing inside an app server then #
# do not use these properties, and the DataSource lookup will #
# use the naming context defined by the app server. #
# #
# The two standard elements of the naming environment are #
# jndicontextfactory and jndicontextproviderurl. If you need #
# additional elements, use the jndicontextcustom property. #
# You can define multiple properties in jndicontextcustom, #
# in name value pairs. Separate the name and value with a #
# semicolon, and separate the pairs with commas. #
# #
# The example shown here is for a standalone program running on #
# a machine that is also running JBoss, so the JDNI context #
# is configured for JBoss (3.0.4). #
# #
# (by default all these are empty) #
#################################################################
#jndicontextfactory=org.jnp.interfaces.NamingContextFactory
#jndicontextproviderurl=localhost:1099
#jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.nameing:org.jnp.interfaces
#jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory
#jndicontextproviderurl=iiop://localhost:900
################################################################
# P6 LOGGING SPECIFIC PROPERTIES #
################################################################
# filter what is logged
# please note this is a precondition for usage of: include/exclude/sqlexpression
# (default is false)
#filter=false
# comma separated list of strings to include
# please note that special characters escaping (used in java) has to be done for the provided regular expression
# (default is empty)
#include =
# comma separated list of strings to exclude
# (default is empty)
#exclude =
# sql expression to evaluate if using regex
# please note that special characters escaping (used in java) has to be done for the provided regular expression
# (default is empty)
#sqlexpression =
#list of categories to exclude: error, info, batch, debug, statement,
#commit, rollback and result are valid values
# (default is info,debug,result,resultset,batch)
#excludecategories=info,debug,result,resultset,batch
# Execution threshold applies to the standard logging of P6Spy.
# While the standard logging logs out every statement
# regardless of its execution time, this feature puts a time
# condition on that logging. Only statements that have taken
# longer than the time specified (in milliseconds) will be
# logged. This way it is possible to see only statements that
# have exceeded some high water mark.
# This time is reloadable.
#
# executionthreshold=integer time (milliseconds)
# (default is 0)
#executionthreshold=
################################################################
# P6 OUTAGE SPECIFIC PROPERTIES #
################################################################
# Outage Detection
#
# This feature detects long-running statements that may be indicative of
# a database outage problem. If this feature is turned on, it will log any
# statement that surpasses the configurable time boundary during its execution.
# When this feature is enabled, no other statements are logged except the long
# running statements. The interval property is the boundary time set in seconds.
# For example, if this is set to 2, then any statement requiring at least 2
# seconds will be logged. Note that the same statement will continue to be logged
# for as long as it executes. So if the interval is set to 2, and the query takes
# 11 seconds, it will be logged 5 times (at the 2, 4, 6, 8, 10 second intervals).
#
# outagedetection=true|false
# outagedetectioninterval=integer time (seconds)
#
# (default is false)
#outagedetection=false
# (default is 60)
#outagedetectioninterval=30
jdbc.properties:
#\u65b9\u8a00
default.dialect=org.hibernate.dialect.Oracle10gDialect
#hibernate.dialect=org.hibernate.dialect.MySQLDialect
#\u6570\u636e\u5e93\u9a71\u52a8
default.driverClassName=com.p6spy.engine.spy.P6SpyDriver
#default.driverClassName=oracle.jdbc.OracleDriver
#default.driverClassName=com.mysql.jdbc.Driver
#default.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
#default.driverClassName=org.h2.Driver
#\u8fde\u63a5\u5730\u5740
default.url=jdbc\:p6spy\:oracle\:thin\:@127.0.0.1\:1521\:orcl
#\u7528\u6237\u540d
default.username=scott
#\u5bc6\u7801
default.password=tiger
#\u5206\u533a\u6570\u91cf(1)
default.partitionCount=2
#\u6bcf\u4e2a\u5206\u533a\u6700\u5c0f\u8fde\u63a5\u6570(2)
default.minConnectionsPerPartition=2
#\u6bcf\u4e2a\u5206\u533a\u6700\u5927\u8fde\u63a5\u6570(10)
default.maxConnectionsPerPartition=10
#\u65b0\u589e\u8fde\u63a5\u589e\u91cf(2)
default.acquireIncrement=2
#\u7a7a\u95f2\u8fde\u63a5\u6709\u6548\u6027\u6d4b\u8bd5\u5468\u671f(240)
default.idleConnectionTestPeriodInMinutes=5
#\u6700\u5927\u7a7a\u95f2\u65f6\u95f4(60)
default.idleMaxAgeInMinutes=10
6.接下来我们新建类JpaConfig配置连接数据库等:
package com.epudge.port.config.ext;
import static com.epudge.port.Constant.ENTITY_PACKAGES_SCAN;
import static com.epudge.port.Constant.JDBC_PROPERTY_SOURCE;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.jolbox.bonecp.BoneCPDataSource;
@Configuration
@PropertySource(JDBC_PROPERTY_SOURCE)
@EnableTransactionManagement
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.epudge.port.jpa.dao")
public class JpaConfig {
@Autowired
protected Environment env;
/**
* 数据源
*
* @return
*/
@Bean
public DataSource dataSource() {
BoneCPDataSource dataSource = new BoneCPDataSource();
dataSource.setDriverClass(env.getProperty("default.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("default.url"));
dataSource.setUsername(env.getProperty("default.username"));
dataSource.setPassword(env.getProperty("default.password"));
dataSource.setPartitionCount(env.getProperty("default.partitionCount", Integer.class));
dataSource.setMaxConnectionsPerPartition(env.getProperty("default.maxConnectionsPerPartition", Integer.class));
dataSource.setMinConnectionsPerPartition(env.getProperty("default.minConnectionsPerPartition", Integer.class));
dataSource.setIdleConnectionTestPeriodInMinutes(env.getProperty("default.idleConnectionTestPeriodInMinutes", Integer.class));
dataSource.setIdleMaxAgeInMinutes(env.getProperty("default.idleMaxAgeInMinutes", Integer.class));
dataSource.setAcquireIncrement(env.getProperty("default.acquireIncrement", Integer.class));
dataSource.setDisableConnectionTracking(true);
return dataSource;
}
/**
* 事务管理器
*
* @param emf
* @return
*/
@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
/**
* 供应商适配器
*
* @return
*/
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabasePlatform(env.getProperty("default.dialect"));
jpaVendorAdapter.setGenerateDdl(false);
return jpaVendorAdapter;
}
/**
* 实体管理器工厂
*
* @return
*/
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean lemfb = new LocalContainerEntityManagerFactoryBean();
lemfb.setDataSource(dataSource());
lemfb.setPersistenceUnitName("default_unit");
lemfb.setJpaVendorAdapter(jpaVendorAdapter());
lemfb.setPackagesToScan(ENTITY_PACKAGES_SCAN);
lemfb.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return lemfb;
}
/**
* 序列号
*
* @return
*/
@Bean
public OracleSequenceMaxValueIncrementer oracleIncr() {
OracleSequenceMaxValueIncrementer oracleIncr =
new OracleSequenceMaxValueIncrementer(dataSource(), "SEQ_IT_NUM");
oracleIncr.setPaddingLength(4);
return oracleIncr;
}
}
7:新建实体类:
package com.epudge.port.jpa.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="JPA_PERSONS")
@Entity
public class Person {
private Integer id;
private String lastName;
private String email;
private int age;
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
service接口:
public interface PersonService {
public java.util.List<Person> getByLastName(String lastName);
}
service接口实现类:
package com.epudge.port.jpa.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.epudge.port.jpa.dao.PersonDao;
import com.epudge.port.jpa.entity.Person;
import com.epudge.port.jpa.service.PersonService;
@Service
public class PersonServiceImpl implements PersonService{
@Autowired
private PersonDao dao;
@Override
public List<Person> getByLastName(String lastName) {
// TODO Auto-generated method stub
return dao.getByLastName(lastName);
}
}
8.jpa接口查询类:
package com.epudge.port.jpa.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.epudge.port.jpa.entity.Person;
public interface PersonDao extends JpaRepository<Person, Integer>{
//根据 lastName 来获取对应的 Person
List<Person> getByLastName(String lastName);
}
9:controller层调用service去dao查询:
package com.epudge.port.mvc;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.epudge.port.jpa.entity.Person;
import com.epudge.port.jpa.service.PersonService;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping
public class HomeController {
@Autowired
private PersonService service;
@RequestMapping(value = "/login")
public String login() throws IOException {
List<Person> s=service.getByLastName("AA");
System.out.println(s+"==========");
return "test";
}
@RequestMapping(value = "/test")
public String test() throws IOException {
List<Person> s=service.getByLastName("AA");
ObjectMapper mapper=new ObjectMapper();
String jsonStr = mapper.writeValueAsString(s);
System.out.println(jsonStr+"====查询结果======");
return "test";
}
}
10:在浏览器输入http://localhost:8080/port/test 控制台出现结果如图:
11:由于个人水平有限,出现的技术问题尽情谅解。
源码下载:点击打开链接
http://download.csdn.net/detail/qq_31968809/9771754