Springboot项⽬搭建总结
Springboot项⽬搭建SpringBoot是⼀个内嵌了web服务器(tomcat,jetty)的可执⾏程序的框架,拟开发的web应⽤不需要war包部署到web服务器上,⽽是作为⼀个可执⾏程
序,启动时把web服务器配置好,加载起来。springboot⽐较适合微服务部署⽅式,不在是把⼀堆应⽤放到⼀个web服务器下,重启web服务器会影响到其他的应⽤,⽽是每个
应⽤独⽴作为⼀个可执⾏程序,启动时把web服务器配置好。springCloud是⼀套微服务开发和治理的框架,是管理⼀⼤堆SpringBoot项⽬之间关联关系的框架,⽐如
SpringBoot项⽬之间远程调⽤,动态服务发现,负载均衡,限流等,可以实现像dubbo⼀样的功能。总结来说 @SpringBootConfiguration注解就是由⼀下注解来组合⽽成
的 1.@Configuration 2.@ComponentScan 3.EnableAutoConfigurationImportSelector.class 4.AutoConfigurationPackages.Registrar.classMyBatis数据源1配置⽂
件配置(这⾥配置两个数据源):package hant.service.datasource;import java.io.IOException;import javax.sql.DataSource;import
org.apachemons.dbcp.BasicDataSource;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.log4j.Logger;import
org.springframework.beans.factory.annotation.Autowired;import t.annotation.Bean;import
t.annotation.Configuration;import t.annotation.Primary;import
t.annotation.PropertySource;import nv.Environment;import
io.support.PathMatchingResourcePatternResolver;import
ansaction.annotation.EnableTransactionManagement;@Configuration@EnableTransactionManagement@PropertySource("classpath:application.properties")@ {"hant.service.dfpay.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory")public class MyBatisConfiguration{ private static final Logger
logger = Logger(MyBatisConfiguration.class); @Autowired private Environment env; @Bean(name="first.datasource") @Primary public
DataSource getDataSource() { BasicDataSource basic = new BasicDataSource();
basic.Property("custom.datasource.driverClassName").trim()); basic.Property("custom.datasource.url").trim());
basic.Property("custom.datasource.username").trim()); basic.Property("custom.datasource.password").trim());
logger.info("init first datasource now ......" + basic.isClosed()); try{ basic.setMaxActive(Integer.Property("spring.datasource.max-active")));
}catch(Exception e){ } try{ basic.setMaxIdle(Integer.Property("spring.datasource.max-idle"))); }catch(Exception e){ } try{
basic.setMinIdle(Integer.Property("spring.datasource.min-idle"))); }catch(Exception e){ } try{
basic.setInitialSize(Integer.Property("spring.datasource.initial-size"))); }catch(Exception e){ } try{
basic.setMinEvictableIdleTimeMillis(Long.Property("spring.datasource.min-evictable-idle-time-millis"))); }catch(Exception e){ } try{
basic.setMaxWait(Long.Property("spring.datasource.max-wait-millis"))); }catch(Exception e){ } try{
basic.setTimeBetweenEvictionRunsMillis(Long.Property("spring.datasource.time-between-eviction-runs-millis"))); }catch(Exception e){ } try{
basic.Property("spring.datasource.validation-query")); }catch(Exception e){ } return basic; } @Bean(name="sqlSessionFactory")
@Primary public SqlSessionFactory sqlSessionFactory() throws IOException{ SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(getDataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.Resources("classpath:net/chrone/merchant/service/dfpay/mapper/*.xml")); SqlSessionFactory sqlSessionFactory =
null; try { sqlSessionFactory = Object(); }catch (Exception e) { e.printStackTrace(); it(0); } return
sqlSessionFactory; } }MyBatis数据源2配置⽂件配置(这⾥配置两个数据源):package hant.service.datasource;import java.io.IOException;import
javax.sql.DataSource;import org.apachemons.dbcp.BasicDataSource;import org.apache.ibatis.session.SqlSessionFactory;import
org.apache.log4j.Logger;batis.spring.SqlSessionFactoryBean;batis.spring.annotation.MapperScan;import
org.springframework.beans.factory.annotation.Autowired;import t.annotation.Bean;import
t.annotation.Configuration;import t.annotation.PropertySource;import
nv.Environment;import
io.support.PathMatchingResourcePatternResolver;@Configuration@PropertySource("classpath:application.properties")@MapperScan(basePackages
= { "hant.service.mapper" }, sqlSessionFactoryRef = "sqlSessionFactoryEpay")public class EpayschConfiguration{ private static final Logger
logger = Logger(EpayschConfiguration.class); @Autowired private Environment env; @Bean(name="second.datasource") public DataSource
getDataSource() { BasicDataSource basic = new BasicDataSource(); basic.Property("spring.datasource.driverClassName").trim());
basic.Property("spring.datasource.url").trim()); basic.Property("spring.datasource.username").trim());
basic.Property("spring.datasource.password").trim()); logger.info("init second datasource now ......" + basic.isClosed()); try{
basic.setMaxActive(Integer.Property("spring.datasource.max-active"))); }catch(Exception e){ } try{
basic.setMaxIdle(Integer.Property("spring.datasource.max-idle"))); }catch(Exception e){ } try{
basic.setMinIdle(Integer.Property("spring.datasource.min-idle"))); }catch(Exception e){ } try{
basic.setInitialSize(Integer.Property("spring.datasource.initial-size"))); }catch(Exception e){ } try{
basic.setMinEvictableIdleTimeMillis(Long.Property("spring.datasource.min-evictable-idle-time-millis"))); }catch(Exception e){ } try{
basic.setMaxWait(Long.Property("spring.datasource.max-wait-millis"))); }catch(Exception e){ } try{
basic.setTimeBetweenEvictionRunsMillis(Long.Property("spring.datasource.time-between-eviction-runs-millis"))); }catch(Exception e){ } try{
basic.Property("spring.datasource.validation-query")); }catch(Exception e){ } return basic; } @Bean(name =
"sqlSessionFactoryEpay") public SqlSessionFactory sqlSessionFactory() throws IOException { SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(getDataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.Resources("classpath:net/chrone/merchant/service/mapper/*.xml")); SqlSessionFactory sqlSessionFactory = null; try
{ sqlSessionFactory = Object(); } catch (Exception e) { e.printStackTrace(); it(0); } return sqlSessionFactory; }}服务器错误页⾯跳转配置
beanpackage fig;import org.t.embedded.ErrorPage;import
org.springframework.boot.autoconfigure.web.ServerProperties;import
org.t.embedded.ConfigurableEmbeddedServletContainer;import org.springframework.http.HttpStatus;public class ServerConfig
extends ServerProperties{ @Override public void customize(ConfigurableEmbeddedServletContainer container) { super.customize(container);
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/404.jsp")); container.addErrorPages(new
ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/500.jsp")); container.addErrorPages(new ErrorPage("/error.jsp")); } }springMVC配置:实现页⾯跳转
package fig;import org.springframework.boot.autoconfigure.web.ServerProperties;import
org.t.embedded.FilterRegistrationBean;import t.annotation.Bean;import
t.annotation.Configuration;import org.springframework.fig.annotation.InterceptorRegistry;import
org.springframework.fig.annotation.ResourceHandlerRegistry;import
org.springframework.fig.annotation.WebMvcConfigurerAdapter;import hant.service.filter.CheckPwdFilter;import
hant.service.filter.CheckURLFilter;import hant.service.interceptor.MyInterceptor;@Configurationpublic class WebConfig
extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/").addResourceLocations("/css/**"); registry.addResourceHandler("/fonts/").addResourceLocations("/fonts/**");
registry.addResourceHandler("/images/").addResourceLocations("/images/**");
registry.addResourceHandler("/scripts/").addResourceLocations("/scripts/**"); } @Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()); } @Bean public FilterRegistrationBean checkPwdFilterRegistration(){ FilterRegistrationBean registration = new
FilterRegistrationBean(); registration.setFilter(new CheckPwdFilter()); String[] interceptController =
{"/mchntCenter","/agent/*","/dfpay/*","/secondarymerchant/*","/ipManager/*","/mobileValidate/*","/ct/*","/public/*","/account/*","/role/*","/accountCheck/*","/cash/*","/queryrefund/ registration.addUrlPatterns(interceptController); registration.setName("checkPwdFilter"); return registration; } /** * 错误页⾯ * @return */ @Bean public
ServerProperties getErrorConfig() { return new ServerConfig(); } }⾃定义package hant.service.interceptor;import
java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import
del.MerLoginUser;import del.MerMenu;import
hant.service.util.ClientSysEvnUtil;import hant.service.util.Constants;import hant.service.util.LogWriter;import
hant.service.util.MD5;import org.apache.log4j.Logger;import org.springframework.web.servlet.HandlerInterceptor;import
org.springframework.web.servlet.ModelAndView;import com.chrone.util.StringUtils;public class MyInt
erceptor implements HandlerInterceptor { private static
final Logger logger = Logger(MyInterceptor.class); @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, Exception arg3) throws Exception { } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2)
throws Exception { String ServletPath(); String ip = IpAddr(request); String agent = Header("user-agent");
if (url.startsWith("/public/")||url.equals("/")||url.equals("/secret/random")||url.equals("")){ request.setAttribute("head", "index"); //输出访问⽇志 try
{ if(!url.startsWith("/images") && !url.startsWith("/css") && !url.startsWith("/scripts")){ logger.info("[操作⽇志]--IP:" + ip + "; 来源:" +
}else{ Session().getAttribute(Constants.LOGIN_SESSION)==null){ if(url.equals("/mchntCenter")){ request.setAttribute("out_tp", "1"); } try{
if(!url.startsWith("/images") && !url.startsWith("/css") && !url.startsWith("/scripts")){ logger.info("[操作⽇志-登录超时]--IP:" + ip + "; 来源:" +
!url.startsWith("/scripts")){ logger.info("[操作⽇志]--IP:" + ip + "; 商户:" + Taccountid() + "; 操作员:" + Id() + "; 访问路径:" + url); } } catch
(Exception e) { // 防御容错 } String flag = MD5.md5(ip+agent); if(!flag.equals(Constants.LOGIN_SESSION_(Id())) && null !=
Constants.LOGIN_SESSION_(Id())){ Session().removeAttribute(Constants.LOGIN_SESSION);
!url.startsWith("/scripts")){ logger.info("[操作⽇志-异地登录]--IP:" + ip + "; 商户:" + Taccountid() + "; 操作员:" + Id() + "; 访问路径:" + url
+ "; flag-n:" + flag + "; flag-s:" + Constants.LOGIN_SESSION_(Id()) ); } }catch(Exception e){ } return false; } if(null ==
Constants.LOGIN_SESSION_(Id())){ Constants.LOGIN_SESSION_ID_MAP.Id(),flag); } if(url.startsWith("/mchntCenter")){
if(StringUtils.Parameter("leftfid"))){ Session().setAttribute("leftfid", Parameter("leftfid")); }
if(StringUtils.Parameter("leftid"))){ Session().setAttribute("leftid", Parameter("leftid")); } if(defaultAuth(url)){//默
认权限 return true; } if(!urlIsAuth(request, url)){ RequestDispatcher("/authError.jsp").forward(request, response); return false;
} return true; } } /** *默认权限 * @return */ public boolean defaultAuth(String url){ List<String> list = new ArrayList<String>();
list.add("/home"); list.add("/secret/random"); list.add("/mchntCenter"); list.add("/loginOut"); list.add("/error");
list.add("/public/loginWithMobileSecurityCode");//⼿机验证 list.add("/user/checkPwd");//检查密码 list.add("/user/checkPayPwd");//检查⽀付密码
list.add("/user/sendEmail");//发送邮件验证 list.add("/user/checkCode");//检查验证码 list.add("/user/checkUserId");//检查⽤户名
list.add("/user/updPwdSucc");//密码修改成功跳转 list.add("/user/sendSmsCode");//发送验证码 list.add("/user/hideKey");//隐藏密钥
list.add("/cash/cash");//提现 list.add("/cash/cashConfirm");//提现 list.add("/cash/cashSub");//提现 list.add("/trans/transAccount");//转账
list.add("/trans/verifyInAccount");//转账 list.add("/trans/transAccountConfirm");//转账 list.add("/trans/transAccountSub");//转账
list.add("/trans/verifyPayPwd");//转账 list.add("/recharge/index");//充值 list.add("/recharge/rechargeConfirm");//充值
list.add("/recharge/rechargeSub");//充值 list.add("/user/forGetPayPwd");//忘记⽀付密码 list.add("/user/newPayPwd");//忘记⽀付密码
list.add("/user/payPwd");//⽀付密码 list.add("/user/loginPwd");//登录密码 list.add("/user/forGetPayPwd");//忘记⽀付密码 list.add("/user/newPayPwd");//
忘记⽀付密码 list.add("/user/payPwd");//⽀付密码 list.add("/user/loginPwd");//登录密码 list.add("/user/updLoginPwd");//登录密码保存
list.add("/user/updNewPayPwd");//忘记⽀付密码保存 list.add("/user/updPayPwd");//修改⽀付密码保存 list.add("/mernotice/updateReadCount");//更新阅读商
户通知信息 for(String l:list){ if(url.startsWith(l)){ return true; } } return false; } /** * url是否有访问权限 * @return */ public boolean
urlIsAuth(HttpServletRequest request,String url){ List<MerMenu> menuInfList = (List<MerMenu>)
if(StringUtils.Url().trim())&&url.Url())){ return true; } } catch (Exception e) { ("异常菜
单:"+menuInf); e.printStackTrace(); } } return false; }}⾃定义url过滤器package hant.service.filter;import java.io.IOException;import
springboot框架的作用java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import javax.servlet.Filter;import
javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import
javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import
org.springframework.stereotype.Component;import hant.service.util.ClientSysEvnUtil;import
hant.service.util.LogWriter;public class CheckURLFilter implements Filter { @Override public void init(FilterConfig filterconfig) throws
ServletException { } @Override public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws
IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletrequest; HttpServletResponse res = (HttpServletResponse)
servletresponse; String urlString = RequestURI(); CharacterEncoding() == null ||
!CharacterEncoding().toUpperCase().equals("UTF-8")){ servletrequest.setCharacterEncoding("UTF-8"); }
LogWriter.info("RemoteAddr:"+IpAddr(req)+" 开始执⾏:"+urlString); long bt = System.currentTimeMillis(); Map<String, String[]> map =
(String[]) (m); LogWriter.info(m+":"+v[0]); } filterchain.doFilter(servletrequest, servletresponse); long et = System.currentTimeMillis();
LogWriter.debug(urlString+"执⾏完毕! 耗时:"+(et-bt)); } @Override public void destroy() { }}⾃定义缓存package fig;import
urrent.ExecutionException;import urrent.TimeUnit;/** * 缓存,超时时间单位:分钟 * * @author zhangzw 2015-05-19 * */public class
Cache<K, V> { // 声明缓存 private LoadingCache<K, V> graphs; /** * * @param timeOut * 分钟 */ public Cache(long timeOut) { Initialize(timeOut); } /** *
初始化缓存容器 */ private void Initialize(long timeOut) { if (timeOut > 0) { graphs = wBuilder() .expireAfterWrite(timeOut, TimeUnit.MINUTES) //
.build(new CacheLoader<K, V>() { public V load(K key) { // 取消默认的⾃动缓存添加器 return null; } }); } else { graphs = wBuilder().build(new
CacheLoader<K, V>() { public V load(K key) { // 取消默认的⾃动缓存添加器 return null; } }); } } /** * 获取缓存信息 * * @param key * @return */
@SuppressWarnings("finally") public V get(K key) { V v = null; try { v = (key); } catch (ExecutionException e) { } finally { return v; } } /** * 设置缓存信
息 * * @param key * @param value */ public void put(K key, V value) { if (null != key && null != value) graphs.put(key, value); } /** * 删除⼀个缓存 * * @param key
*/ public void remove(String key) { graphs.invalidate(key); } /** * 清空全部缓存 */ public void clearAll() { graphs.invalidateAll(); }}springboot启动main⽅法package
hant.service;import org.springframework.boot.SpringApplication;import
org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import
org.t.web.SpringBootServletInitializer;import t.annotation.ImportResource;import
ansaction.annotation.EnableTransactionManagement;//@ServletComponentScan@SpringBootApplication@EnableTransactionManagement@ImportResource class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return
builder.sources(Application.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }Springboot 常⽤注解
@SpringBootApplication:包含@Configuration、@EnableAutoConfiguration、@ComponentScan通常⽤在主类上。@Repository:⽤于标注数据访问组件,即DAO组
件。@Service:⽤于标注业务层组件。 @RestController:⽤于标注控制层组件(如struts中的action),包含@Controller和@ResponseBody。@ResponseBody:表⽰该⽅
法的返回结果直接写⼊HTTP response body中⼀般在异步获取数据时使⽤,在使⽤@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果
不会被解析为跳转路径,⽽是直接写⼊HTTP response body中。⽐如异步获取json数据,加上@responsebody后,会直接返回json数据。@Component:泛指组件,当组
件不好归类的时候,我们可以使⽤这个注解进⾏标注。@ComponentScan:组件扫描。个⼈理解相当于<context:component-scan>,如果扫描到有@Component
@Controller @Service等这些注解的类,则把这些类注册为bean。@Configuration:指出该类是 Bean 配置的信息源,相当于XML中的<beans></beans>,⼀般加在主类
上。@Bean:相当于XML中的<bean></bean>,放在⽅法的上⾯,⽽不是类,意思是产⽣⼀个bean,并交给spring管理。@EnableAutoConfiguration:让 Spring Boot 根据应
⽤所声明的依赖来对 Spring 框架进⾏⾃动配置,⼀般加在主类上。@AutoWired:byType⽅式。把配置好的Bean拿来⽤,完成属性、⽅法的组装,它可以对类成员变量、⽅法
及构造函数进⾏标注,完成⾃动装配的⼯作。当加上(required=false)时,就算不到bean也不报错。@Qualifier:当有多个同⼀类型的Bean时,可以⽤
@Qualifier("name")来指定。与@Autowired配合使⽤@Resource(name="name",type="type"):没有括号内内容的话,默认byName。与@Autowired⼲类似的事。
@RequestMapping:RequestMapping是⼀个⽤来处理请求地址映射的注解,可⽤于类或⽅法上。⽤于类上,表⽰类中的所有响应请求的⽅法都是以该地址作为⽗路径。该
注解有六个属性:params:指定request中必须包含某些参数值时,才让该⽅法处理。headers:指定request中必须包含某些指定的header值,才能让该⽅法处理请求。value:
指定请求的实际地址,指定的地址可以是URI Template 模式method:指定请求的method类型, GET、POST、PUT、DELETE等consumes:指定处理请求的提交内容类型
(Content-Type),如application/json,text/html;produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回
@RequestMapping(value="/testRequestMapping",method= RequestMethod.POST )案例:@Controller@RequestMapping("/user")public class UserController {
private Logger logger = Logger(LoginController.class); @Autowired private MerLoginUserService merLoginUserService;
@RequestMapping("user_list") public String list(HttpServletRequest request,String start,Model model){ return "user/user_list"; }} @RequestParam:⽤在⽅法的参数前⾯。@RequestParam String a 相当于String a =Parameter("a")。@PathVariable:路径变量。参数与⼤括号⾥的名字⼀样要相同。RequestMapping("user/get/mac/{macAddress}")public String getByMacAddress(@PathVariable String macAddress){� //do
something;}} @ProfilesSpring Profiles提供了⼀种隔离应⽤程序配置的⽅式,并让这些配置只能在特定的环境下⽣效。任何@Component或@Configuration都能被
@Profile标记,从⽽限制加载它的时机。@Configuration@@Profile("prod")public class ProductionConfiguration { // ...}}⽐如:@Profile("product")⽣产环境下加载 @Profile("dev")开发环境下加载 @Profile("test")测试环境下加载 @ConfigurationPropertiesSpring Boot将尝试校验外部的配置,默认使⽤JSR-
303(如果在classpath路径中)。你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解:
@Component@@ConfigurationProperties(prefix="connection")public class ConnectionSettings {@@NotNullprivate InetAddress remoteAddress;// ... getters and setters}} 全局异常处理@ControllerAdvice:包含@Component。可以被扫描到。统⼀处理异常。@ExceptionHandler(Exception.class):⽤在⽅法上⾯表⽰遇到这个异常就执⾏以下⽅法。
================================================================================================spring-boot默认提供内嵌的tomcat,所以打包直接⽣成jar包,⽤java -jar命令就可以启动。但是,有时候我们更希望⼀个tomcat来管理多个项⽬,这种情况下就需要项⽬是war格式的包⽽不是jar格式的包。spring-boot同样提供了解决⽅案,只需要简单的⼏步更改就可以了,这⾥提供maven项⽬的解决⽅法:1.将springboot项⽬的启动类Application.java继承SpringBootServletInitializer并重写configure⽅法@SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) throws Exception {SpringApplication.run(Application.class, args); }}2.在l⽂件中,project下⾯增加package标签
<packaging>war</packaging>3.还是在l⽂件中,dependencies下⾯添加<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>或者这种⽅法:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论