web框架 Spring+SpringMvc+Jpa 纯注解搭建
2019-11-20 16:03:31来源:博客园 阅读 ()
web框架 Spring+SpringMvc+Jpa 纯注解搭建
0.jar包依赖 maven pom.xml
<properties> <spring_version>4.3.25.RELEASE</spring_version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.23.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.10.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> </dependencies>
1.可被 servlet3.0 容器自动扫描加载的配置文件,位置不限,作用同 web.xml
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class<?>[] getRootConfigClasses() { // spring容器的配置文件 return new Class[]{SpringConfig.class}; } protected Class<?>[] getServletConfigClasses() { // springMVC容器的配置文件 return new Class[]{MvcConfig.class}; } protected String[] getServletMappings() { // 被DisatcjerServlet接管的请求路径 return new String[]{"/"}; } }
2.spring容器的配置文件,管理 除被springMvc容器管理(如控制器) 以外的所有对象,可防止织入事务切面时不生效的情况发生
package com.sw946.spring_demo.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.EnableWebMvc;
//开启注解扫描功能,并设置扫描范围,排除springMvc的配置文件和Controller组件 @ComponentScan(basePackages = {"com.sw946.spring_demo"},excludeFilters = @ComponentScan.Filter({EnableWebMvc.class, Controller.class})) public class SpringConfig { }
3.springMvc容器的配置文件,仅管理自定义的控制器,与spring容器为互补
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; //开启springMvc注解扫描功能 @EnableWebMvc //仅扫描有@Controller注解的类纳入容器管理 @ComponentScan(basePackages = "com.sw946.spring_demo",includeFilters = @Filter(Controller.class),useDefaultFilters = false) public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void configureViewResolvers(ViewResolverRegistry registry) { //配置视图解析器(可选) registry.jsp("/", ".jsp"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { //配置静态资源处理器为web容器默认处理器 configurer.enable(); } }
4.JPA(数据持久化层)的配置文件,本例使用hibernate + mysql, 持久化框架和数据均可替换,配置思路相同
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; //申明为spring配置文件,spring若开启注解扫描,将会将此类作为spring容器配置的一部分 @Configuration //开启jpa注解扫描,并给定范围,jpa会为继承了JpaRepository接口的接口生成实现类 @EnableJpaRepositories(basePackages = "com.sw946.spring_demo.repository") //开启事务管理功能 @EnableTransactionManagement public class JpaConfig { @Bean public DataSource productDB() { //配置数据源,按实际要连接的数据库配置 DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC"); ds.setUsername("admin"); ds.setPassword("admin"); return ds; } @Bean public JpaVendorAdapter jpaVendorAdapter() { //配置ORM框架,这里为hibernate HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setDatabase(Database.MYSQL); adapter.setShowSql(true); adapter.setGenerateDdl(false); adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); return adapter; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter){ //配置实体管理器工厂 LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(dataSource); emf.setJpaVendorAdapter(jpaVendorAdapter); emf.setPackagesToScan("com.sw946.spring_demo.entity"); //给定实体类的扫描范围,会扫描@Entity注解的类 return emf; } @Bean public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean factoryBean) { //配置事务管理器,依赖于实体管理器(需要连接会话) return new JpaTransactionManager(factoryBean.getObject()); } }
框架配置完成,下面为使用示例:
a.控制器(注意包的位置,根据扫描范围配置建立)
import com.sw946.spring_demo.repository.GradeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class HomeController { @Autowired private GradeRepository gradeRepository; @RequestMapping("/home") @ResponseBody public String home() { return gradeRepository.findLaster().toString(); } }
b.持久层(因示例简单,忽略服务层)
import com.sw946.spring_demo.entity.Grade; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface GradeRepository extends JpaRepository<Grade,String>{ List<Grade> findByIdLessThan(String id); //方法名查询,jpa提供 //JPql、原生sql查询 @Query(nativeQuery=true, value = "select * from grade order by id desc limit 0,1") Grade findLaster(); }
package com.sw946.spring_demo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Date; @Entity public class Grade { @Id private String id; private String name; @Column(name = "create_time") private Date createTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "Grade{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", createTime=" + createTime + '}'; } }
c.数据库表
CREATE TABLE `grade` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `create_time` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; INSERT INTO `grade` (`id`, `name`, `create_time`) VALUES ('1', '2019', '2019-11-18 15:50:41'); INSERT INTO `grade` (`id`, `name`, `create_time`) VALUES ('4', '2020', '2019-11-18 17:32:56');
tomcat运行,访问 127.0.0.1:端口号/home ,即可看到数据库返回的json字符串,框架搭建完成!
原文链接:https://www.cnblogs.com/webwei2017/p/11899074.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- Java--反射(框架设计的灵魂)案例 2020-06-11
- Java--反射(框架设计的灵魂) 2020-06-11
- 与JAVA集合相遇 2020-06-11
- Spring WebFlux 学习笔记 - (一) 前传:学习Java 8 Stream Ap 2020-06-11
- eclipse下创建Maven项目(包含webapp目录结构) 2020-06-09
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash