spring boot可导出war包开发环境搭建,包括数据库、缓存、拦截器设置

1.我自己的文件结构图


1.配置maven依赖,里面的依赖包包含了数据库、缓存等所使用的jar包

<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>
  <groupId>Springboot</groupId>
  <artifactId>Springboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
</parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-tomcat</artifactId>  
        <scope>provided</scope>  
    </dependency>
    <dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency> 
    <dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-actuator</artifactId>
	</dependency>
	<dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-data-jpa</artifactId>  
    </dependency> 
	<dependency>  
        <groupId>mysql</groupId>  
        <artifactId>mysql-connector-java</artifactId>  
    </dependency>
    <dependency>  
        <groupId>org.apache.poi</groupId>  
        <artifactId>poi</artifactId>  
        <version>3.11</version>  
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-devtools</artifactId>
	    <optional>true</optional>
	    <scope>true</scope>
	</dependency>
	<dependency>
	    <groupId>net.sf.ehcache</groupId>
	    <artifactId>ehcache</artifactId>
	</dependency>
	<dependency>
	    <groupId>org.springframework</groupId>
	     <artifactId>spring-context-support</artifactId>
	</dependency>
	
</dependencies>
  
  
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
      <plugin>
	     <groupId>org.springframework.boot</groupId>
	     <artifactId>spring-boot-maven-plugin</artifactId>
	     <configuration>
	        <fork>true</fork>
	     </configuration>
	 </plugin>
    </plugins>
  </build>
</project>

2.配置application.properties文件,第一二行允许不使用密码访问url+shutdown关闭服务,上线应用请自行修改。

endpoints.shutdown.enabled=true
endpoints.shutdown.sensitive=false
server.port=80
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = *****
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS    
spring.jpa.database = MYSQL
# Show or not log for each sql query    
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)    
spring.jpa.hibernate.ddl-auto = update
# Naming strategy    
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)    
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.thymeleaf.cache=false
spring.jpa.properties.hibernate.show_sql=true
3.spring boot 启动文件 ServletInitializer.java,开发过程中可使用运行方式-》java应用程序启动tomcat,访问url+shutdown关闭,一定要用post方式访问!!!

package main;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class ServletInitializer extends SpringBootServletInitializer {
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {  
        return application.sources(ServletInitializer.class);  
    }
	
	public static void main(String[] args) {
        SpringApplication.run(ServletInitializer.class, args);
    }
	
}
4.配置ehcache.xml 和启动文件CacheConfiguration.java。这里只配置了一个name,并没有配置默认使用的,自行使用添加吧。

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <cache name="UserRespositroy"
           maxEntriesLocalHeap="200"
           timeToLiveSeconds="10">
    </cache>
</ehcache>
package main.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
//标注启动了缓存
@EnableCaching
public class CacheConfiguration {
	/*
     * ehcache 主要的管理器
     */
    @Bean(name = "appEhCacheCacheManager")
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
        return new EhCacheCacheManager (bean.getObject ());
    }

    /*
     * 据shared与否的设置,Spring分别通过CacheManager.create()或new CacheManager()方式来创建一个ehcache基地.
     */
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
        cacheManagerFactoryBean.setConfigLocation (new ClassPathResource ("ehcache.xml"));
        cacheManagerFactoryBean.setShared (true);
        return cacheManagerFactoryBean;
    }
}
5.拦截器UserInterceptor.java  preHandle中返回true才继续执行。

package main.interceptors; 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserInterceptor implements HandlerInterceptor  {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO 自动生成的方法存根
		System.out.println("11111111");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO 自动生成的方法存根
		System.out.println("22222222222");
	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		// TODO 自动生成的方法存根
		System.out.println("333333333333");
		return true;
	}

	

}
6.配置拦截器MyConfig.java,addPathPatterns为需要拦截的通配,excludePathPatterns为不需要的,可以是范类型,还有很多其他方法,没试过! 尴尬

package main.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import main.interceptors.UserInterceptor;

@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// TODO 自动生成的方法存根
		registry.addInterceptor(new UserInterceptor()).addPathPatterns("/**").excludePathPatterns("/");
		super.addInterceptors(registry);
	}

}

7.其他controller/model/service,(IndexController.java/User.java/UserRespositroy.java),其中UserRespositroy.java 中@Query使用,如果没有nativeQuery = true 则使用的是数据库的实体类文件,这里对应的就是User.java,select中User首字母要大些,如果有就是使用源生sql语句。
package main.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import main.model.User;
import main.service.UserRespositroy;

@Controller
@EnableAutoConfiguration
public class IndexController {
	@Autowired
	UserRespositroy userRespositroy;
	
	@RequestMapping("/")
	@ResponseBody
	public String index(){
		return "hello world";
	}
	
	
	@RequestMapping("/hello/{id}")
	@ResponseBody
	
	public User hello(@PathVariable int id){
		
		User user = userRespositroy.findOneUser("1111212", 1);
		System.out.println(id);
		
		return user;
	}
	
}

package main.model;

import java.math.BigDecimal;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	private String name;

	private int height1;

	private int sex;

	private Date birthday;

	private Date sendtime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss

	private BigDecimal price;

	private float floatprice;

	private double doubleprice;

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public int getHeight1() {
		return height1;
	}

	public int getSex() {
		return sex;
	}

	public Date getBirthday() {
		return birthday;
	}

	public Date getSendtime() {
		return sendtime;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public float getFloatprice() {
		return floatprice;
	}

	public double getDoubleprice() {
		return doubleprice;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setHeight1(int height1) {
		this.height1 = height1;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public void setSendtime(Date sendtime) {
		this.sendtime = sendtime;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public void setFloatprice(float floatprice) {
		this.floatprice = floatprice;
	}

	public void setDoubleprice(double doubleprice) {
		this.doubleprice = doubleprice;
	}

}

package main.service;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import main.model.User;

@EnableCaching
public interface UserRespositroy extends JpaRepository<User, Integer> {
	@Cacheable(cacheNames="UserRespositroy")
	User findById(int id);
	
	@Query(value = "select * from user where name = ?1 and sex = ?2", nativeQuery = true)
	User findOneUser(String name, int sex);
}






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦里藍天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值