Maven工程搭建spring boot+spring mvc+JPA的示例
发布时间:2020-05-23 19:53:48 所属栏目:Java 来源:互联网
导读:本文介绍了Maven工程搭建springboot+springmvc+JPA的示例,分享给大家,具体如下:
|
本文介绍了Maven工程搭建spring boot+spring mvc+JPA的示例,分享给大家,具体如下: 添加Spring boot支持,引入相关包: 1、maven工程,少不了pom.xml,spring boot的引入可参考官网: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope><!-- 编译需要而发布不需要的jar包 --> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--jpa的jar包 ,操作数据库的--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.2</version> </dependency> <!-- shiro ehcache --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> <finalName>name</finalName> </build> 2、以上代码引入了spring boot。spring mvc 和jpa,以及mysql数据库的驱动jar; 编写启动类,并加装配置文件: 1、启动类如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import java.io.IOException;
import com.my.config.CommonProperties;
@SpringBootApplication
@EnableAutoConfiguration
@EnableJpaAuditing
public class Application {
public static void main(String[] args) throws IOException{
String loc = CommonProperties.loadProperties2System(System.getProperty("spring.config.location"));
System.getProperties().setProperty("application.version",CommonProperties.getVersion(Application.class));
System.getProperties().setProperty("app.home",loc + "/..");
SpringApplication.run(Application.class,args);
}
}
2、配置文件的位置放到classpath外边,方便在不重新打包的情况下修改,spring boot工程一般都打成jar包:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.springframework.util.StringUtils;
public final class CommonProperties {
public static final String PPT_KEY_APP_HOME = "app.home";
public static final String DEFAULT_APP_HOME = "./";
public static final String getAppHome() {
return System.getProperty("./","./");
}
public static String loadProperties2System(String location) throws IOException {
String configLocation = location;
File cnf;
if (!StringUtils.hasLength(location)) {
configLocation = "./config";
cnf = new File(configLocation);
if (!cnf.exists() || !cnf.isDirectory()) {
configLocation = "../config";
cnf = new File(configLocation);
}
} else {
cnf = new File(location);
}
File[] arg2 = cnf.listFiles();
int arg3 = arg2.length;
for (int arg4 = 0; arg4 < arg3; ++arg4) {
File file = arg2[arg4];
if (file.isFile() && file.getName().endsWith(".properties")) {
Properties ppt = new Properties();
FileInputStream fi = new FileInputStream(file);
Throwable arg8 = null;
try {
ppt.load(fi);
System.getProperties().putAll(ppt);
} catch (Throwable arg17) {
arg8 = arg17;
throw arg17;
} finally {
if (fi != null) {
if (arg8 != null) {
try {
fi.close();
} catch (Throwable arg16) {
arg8.addSuppressed(arg16);
}
} else {
fi.close();
}
}
}
}
}
return configLocation;
}
public static String getVersion(Class<?> clazz) {
Package pkg = clazz.getPackage();
String ver = pkg != null ? pkg.getImplementationVersion() : "undefined";
return ver == null ? "undefined" : ver;
}
将配置文件放到jar包同级目录的config文件夹下,包括日志配置,application.yml文件,其他配置文件等; 编写自动配置类 用于扫描compan*,代替spring mvc的spring.xml配置文件:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {
"com.my.rs","com.my.service","com.my.repository"})
public class AppAutoConfiguration {
}
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 预配置
* */
@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter{
@Bean
public HttpMessageConverters customConverters() {
return new HttpMessageConverters();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**")
// .addResourceLocations("classpath:/META-INF/resources/**");
}
编写rs,service,repository
package com.my.rs;
import java.util.List;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.my.entity.User;
@RequestMapping({"/api/user"})
public interface UserRS {
@RequestMapping(value="/add",method={RequestMethod.POST})
@ResponseBody
public User saveUser(@RequestBody User user);
@RequestMapping(value="/update",method={RequestMethod.POST})
@ResponseBody
public User updateUser(@RequestBody User user);
@RequestMapping(value="/delete",method={RequestMethod.POST,RequestMethod.DELETE})
public void deleteUser(@RequestParam String[] userIds);
@RequestMapping(value="/get",method={RequestMethod.GET})
@ResponseBody
public User getUser(@RequestParam String userId);
@RequestMapping(value="/query/all",method={RequestMethod.GET})
public List<User> queryAll();
@RequestMapping(value="/query/byName",method={RequestMethod.GET})
public List<User> queryByName(@RequestParam String name);
@RequestMapping(value="/query/byParentId",method={RequestMethod.GET})
public List<User> queryChildren(@RequestParam String parentId);
//无参数分页查询
@RequestMapping(value="/query/page",method={RequestMethod.GET})
public List<User> queryByPage(@RequestParam int pageNo,@RequestParam int pageSize,@RequestBody(required=false) User user);
}
package com.my.rs.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.my.entity.User;
import com.my.rs.UserRS;
import com.my.service.UserService;
@RestController
public class UserRSImpl implements UserRS{
public static Logger logger = LoggerFactory.getLogger(UserRSImpl.class);
@Autowired
UserService _userService;
@Override
public User saveUser(@RequestBody User user){
try {
return _userService.save(user);
} catch (Throwable e) {
logger.error(e.getMessage(),e);
throw e;
}
}
@Override
public User updateUser(@RequestBody User user) {
return _userService.update(user);
}
@Override
public void deleteUser(String[] userIds) {
for (String userId : userIds) {
_userService.deleteById(userId);
}
}
@Override
public List<User> queryAll() {
return _userService.queryAll();
}
@Override
public List<User> queryByName(String name) {
return _userService.findByName(name);
}
@Override
public List<User> queryChildren(String parentId) {
return _userService.findByParentId(parentId);
}
@Override
public User getUser(String userId) {
return _userService.findById(userId);
}
@Override
public List<User> queryByPage(int pageNo,int pageSize,User user) {
return null;
}
}
package com.my.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.my.entity.User;
import com.my.repository.UserRepository;
@Service
public class UserService extends BaseService<User>{
@Autowired
UserRepository _userRepository;
public List<User> findByName(String name){
return _userRepository.findByName(name);
}
public List<User> findByParentId(String parentId){
return _userRepository.findByParentId(parentId);
}
}
package com.my.repository;
import java.util.List;
import com.my.entity.User;
public interface UserRepository extends BaseRepository<User>{
List<User> findByName(String name);
List<User> findByParentId(String parentId);
}
以上采用了分层模式,有点繁琐,但是对之后修改每层的业务逻辑比较方便 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
