Spring boot之SpringApplicationBuilder,@@Configuration注解,@Component注解
SpringApplicationBuilder:
该方法的作用是可以把项目打包成war包
需要配置启动类,pom.xml文件等,具体见:http://blog.csdn.net/linzhiqiang0316/article/details/52601292
@SpringBootApplication
public class FavoritesApplication extends SpringBootServletInitializer{ /**
* 如此配置打包后可以用tomcat下使用
* @param application
* @return
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FavoritesApplication.class);
} public static void main(String[] args) {
SpringApplication.run(FavoritesApplication.class, args);
}
}
@Configuration注解:
从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
@Configuration
public class WebConfiguration { @Bean
public FilterRegistrationBean filterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new SecurityFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
} }
public class SecurityFilter implements Filter {
protected Logger logger = Logger.getLogger(this.getClass());
private static Set<String> GreenUrlSet = new HashSet<String>();
@Autowired
private UserRepository userRepository;
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
GreenUrlSet.add("/login");
GreenUrlSet.add("/register");
GreenUrlSet.add("/index");
GreenUrlSet.add("/forgotPassword");
GreenUrlSet.add("/newPassword");
GreenUrlSet.add("/tool");
}
@Override
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest) srequest;
String uri = request.getRequestURI();
if (request.getSession().getAttribute(Const.LOGIN_SESSION_KEY) == null) {
Cookie[] cookies = request.getCookies();
if (containsSuffix(uri) || GreenUrlSet.contains(uri) || containsKey(uri)) {
logger.debug("don't check url , " + request.getRequestURI());
filterChain.doFilter(srequest, sresponse);
return;
}else if (cookies!=null) {
boolean flag = true;
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals(Const.LOGIN_SESSION_KEY)) {
if(StringUtils.isNotBlank(cookie.getValue())){
flag = false;
}else{
break;
}
String value = getUserId(cookie.getValue());
Long userId = 0l;
if (userRepository == null) {
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
userRepository = (UserRepository) factory.getBean("userRepository");
}
if(StringUtils.isNotBlank(value)){
userId = Long.parseLong(value);
}
User user = userRepository.findOne(userId);
String html = "";
if(null == user){
html = "<script type=\"text/javascript\">window.location.href=\"_BP_login\"</script>";
}else{
logger.info("userId :" + user.getId());
request.getSession().setAttribute(Const.LOGIN_SESSION_KEY, user);
String referer = this.getRef(request);
if(referer.indexOf("/collect?") >= 0 || referer.indexOf("/lookAround/standard/") >= 0
|| referer.indexOf("/lookAround/simple/") >= 0){
filterChain.doFilter(srequest, sresponse);
return;
}else{
html = "<script type=\"text/javascript\">window.location.href=\"_BP_\"</script>";
}
}
html = html.replace("_BP_", Const.BASE_PATH);
sresponse.getWriter().write(html);
/**
* HttpServletResponse response = (HttpServletResponse) sresponse;
response.sendRedirect("/");
*/
}
}
if(flag){
//跳转到登陆页面
String referer = this.getRef(request);
logger.debug("security filter, deney, " + request.getRequestURI());
String html = "";
if(referer.contains("/collect?") || referer.contains("/lookAround/standard/")
|| referer.contains("/lookAround/simple/")){
html = "<script type=\"text/javascript\">window.location.href=\"_BP_login\"</script>";
}else{
html = "<script type=\"text/javascript\">window.location.href=\"_BP_index\"</script>";
}
html = html.replace("_BP_", Const.BASE_PATH);
sresponse.getWriter().write(html);
}
}else{
//跳转到登陆页面
String referer = this.getRef(request);
logger.debug("security filter, deney, " + request.getRequestURI());
String html = "";
if(referer.contains("/collect?") || referer.contains("/lookAround/standard/")
|| referer.contains("/lookAround/simple/")){
html = "<script type=\"text/javascript\">window.location.href=\"_BP_login\"</script>";
}else{
html = "<script type=\"text/javascript\">window.location.href=\"_BP_index\"</script>";
}
html = html.replace("_BP_", Const.BASE_PATH);
sresponse.getWriter().write(html);
// HttpServletResponse response = (HttpServletResponse) sresponse;
//response.sendRedirect("/");
}
}else{
filterChain.doFilter(srequest, sresponse);
}
}
/**
* @param url
* @return
* @author neo
* @date 2016-5-4
*/
private boolean containsSuffix(String url) {
if (url.endsWith(".js")
|| url.endsWith(".css")
|| url.endsWith(".jpg")
|| url.endsWith(".gif")
|| url.endsWith(".png")
|| url.endsWith(".html")
|| url.endsWith(".eot")
|| url.endsWith(".svg")
|| url.endsWith(".ttf")
|| url.endsWith(".woff")
|| url.endsWith(".ico")
|| url.endsWith(".woff2")) {
return true;
} else {
return false;
}
}
/**
* @param url
* @return
* @author neo
* @date 2016-5-4
*/
private boolean containsKey(String url) {
if (url.contains("/media/")
|| url.contains("/login")||url.contains("/user/login")
|| url.contains("/register")||url.contains("/user/regist")||url.contains("/index")
|| url.contains("/forgotPassword")||url.contains("/user/sendForgotPasswordEmail")
|| url.contains("/newPassword")||url.contains("/user/setNewPassword")
|| (url.contains("/collector") && !url.contains("/collect/detail/"))
|| url.contains("/collect/standard/")||url.contains("/collect/simple/")
|| url.contains("/user")||url.contains("/favorites")||url.contains("/comment")
|| url.startsWith("/lookAround/standard/")
|| url.startsWith("/lookAround/simple/")
|| url.startsWith("/user/")
|| url.startsWith("/feedback")
|| url.startsWith("/standard/")
|| url.startsWith("/collect/standard/lookAround/")
|| url.startsWith("/collect/simple/lookAround/")) {
return true;
} else {
return false;
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
public String codeToString(String str) {
String strString = str;
try {
byte tempB[] = strString.getBytes("ISO-8859-1");
strString = new String(tempB);
return strString;
} catch (Exception e) {
return strString;
}
}
public String getRef(HttpServletRequest request){
String referer = "";
String param = this.codeToString(request.getQueryString());
if(StringUtils.isNotBlank(request.getContextPath())){
referer = referer + request.getContextPath();
}
if(StringUtils.isNotBlank(request.getServletPath())){
referer = referer + request.getServletPath();
}
if(StringUtils.isNotBlank(param)){
referer = referer + "?" + param;
}
request.getSession().setAttribute(Const.LAST_REFERER, referer);
return referer;
}
public String getUserId(String value){
try {
String userId = Des3EncryptionUtil.decode(Const.DES3_KEY,value);
userId = userId.substring(0,userId.indexOf(Const.PASSWORD_KEY));
return userId;
}catch (Exception e){
logger.error("解析cookie异常:",e);
}
return null;
}
}
@Component:
关于Spring的@Component、@Repository、@Service、@Controller四个注解的区别,查阅了spring的官方文档:http://spring.io/search,文档中只是说了组件的注解要在组件处,service的注解要用在service处,但是他们的定义却没有区别。
问题:
1.那既然没有区别,为什么要分开来定义四个注解呢?
2.既然如他定义中说的,使用具体场景如下:
@Repository注解:用于标注数据访问组件,即DAO组件
@Service注解:用于标注业务层组件
@Controller注解:用于标注控制层组件(如struts中的action)
@Component注解:泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Service
public class UserServiceImpl implements UserService { }
@Repository
public class UserDaoImpl implements UserDao { } getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“***”)
这样来指定,这种bean默认是单例的,如果想改变,可以使用@Service(“beanName”)
@Scope(“prototype”)来改变。可以使用以下方式指定初始化方法和销毁方法(方法名任意): @PostConstruct public void init() { }
总结:
1.用IDEA时,dao层没有注解idea会在service实现层的声明这个dao报错,加上这些注解之后就不会提示错误了,但是可以运行没有问题。
2.以上注解的作用基本相同,不同是标注这是什么层面,经过测试在dao层使用controller注解也可以正常运行。
Spring boot之SpringApplicationBuilder,@@Configuration注解,@Component注解的更多相关文章
- Spring Boot 最核心的 25 个注解,都是干货!
学习和应用 Spring Boot 有一些时间了,你们对 Spring Boot 注解了解有多少呢?今天栈长我给大家整理了 Spring Boot 最核心的 25 个注解,都是干货! 你所需具备的基础 ...
- Spring Boot 最核心的 3 个注解详解
最近面试一些 Java 开发者,他们其中有些在公司实际用过 Spring Boot, 有些是自己兴趣爱好在业余自己学习过.然而,当我问他们 Spring Boot 最核心的 3 个注解是什么,令我失望 ...
- 精尽Spring Boot源码分析 - 剖析 @SpringBootApplication 注解
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- Spring Boot入门(三):使用Scheduled注解实现定时任务
在程序开发的过程中,经常会使用定时任务来实现一些功能,比如: 系统依赖于外部系统的非核心数据,可以定时同步 系统内部一些非核心数据的统计计算,可以定时计算 系统内部的一些接口,需要间隔几分钟或者几秒执 ...
- 自定义的Spring Boot starter如何设置自动配置注解
本文首发于个人网站: 在Spring Boot实战之定制自己的starter一文最后提到,触发Spring Boot的配置过程有两种方法: spring.factories:由Spring Boot触 ...
- Spring Boot 项目学习 (二) MySql + MyBatis 注解 + 分页控件 配置
0 引言 本文主要在Spring Boot 基础项目的基础上,添加 Mysql .MyBatis(注解方式)与 分页控件 的配置,用于协助完成数据库操作. 1 创建数据表 这个过程就暂时省略了. 2 ...
- Spring Boot @EnableAutoConfiguration和 @Configuration的区别
Spring Boot @EnableAutoConfiguration和 @Configuration的区别 在Spring Boot中,我们会使用@SpringBootApplication来开启 ...
- Inspection info: Checks Spring Boot application .properties configuration files. Highlights unresolved and deprecated configuration keys and in
Cannot resolve class or package ‘jdbc’ less… (Ctrl+F1) Inspection info: Checks Spring Boot applicati ...
- spring boot: EL和资源 (一般注入说明(二) @Service注解 @Component注解)
@Service用于标注业务层组件 : 将当前类注册为spring的Bean @Controller用于标注控制层组件(如struts中的action) @Repository用于标注数据访问组件,即 ...
随机推荐
- jQuery 动态标签生成插件
前言: 最近对js的插件封装特别感兴趣,无耐就目前的技术想做到js的完全封装,还是有一定困难,就基于jQuery封装了一个小的插件,而且是基于对象级开发的,不是添加全局方法.高深的语法几乎没有,就有一 ...
- windows设置代理.bat 脚本
按照下列脚本复制到记事本中,保存,重命名后缀为.bat,使用时双击即可. 设置代理.bat,修改下列脚本中的代理地址和端口号 @echo off echo 开始设置IE代理上网 reg add &qu ...
- PIE的使用
实际上是指的是一个名为pie的htc文件,即pie.htc,使用CSS的behavior行为,可以调用此文件,然后让IE也能实现一些常见的 CSS3效果,如圆角(border-radius),盒阴影( ...
- 生死相依:说说JQuery中die()、live()详解[翻译]
一个web前端工程师,应该知道jquery的.live()函数,知道它是做什么用的,但是不知它是怎么样工作的,使用起来也是不得得心应手的,甚至也没听说过.die()(去掉bind事件).即使你能熟悉这 ...
- 简单几招,解决jQuery.getJSON的缓存问题
今天做测试工作,发现了一个令我费解的问题,jquery的getJson方法在firefox上运行可以得到返回的结果,但是在ie8上测试,竟发现没有发送请求,故不能取到任何返回的结果,经历了一翻周折,找 ...
- [php]mysql操作流程
这种是比较老的一种mysql连接方法 1.连接数据库 $this->con = mysql_connect($this->host, $this->user, $this->p ...
- 详细讲解安全升级MySQL的方法
MySQL升级是非常必要的. 我们在Percona Support上列出了关于MySQL升级最佳实践的各种问题.这篇文章推荐了一些不同情况下升级MySQL的方法. 为什么MySQL升级是必须的? 原因 ...
- C# Json字符串反序列化
using DevComponents.DotNetBar; using MyControl; using Newtonsoft.Json; using System; using System.Co ...
- E - Sudoku HDU - 5547 (搜索+暴力)
题目链接:https://cn.vjudge.net/problem/HDU-5547 具体思路:对于每一位上,我们可以从1到4挨着去试, 具体判断这一位可不可以的时候,看当前这一位上的行和列有没有冲 ...
- solr配置中文分词器——(十二)
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAqcAAAGzCAIAAACdKClDAAAgAElEQVR4nOydd5gUxdbGx5xASZKXLB