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注解的更多相关文章

  1. Spring Boot 最核心的 25 个注解,都是干货!

    学习和应用 Spring Boot 有一些时间了,你们对 Spring Boot 注解了解有多少呢?今天栈长我给大家整理了 Spring Boot 最核心的 25 个注解,都是干货! 你所需具备的基础 ...

  2. Spring Boot 最核心的 3 个注解详解

    最近面试一些 Java 开发者,他们其中有些在公司实际用过 Spring Boot, 有些是自己兴趣爱好在业余自己学习过.然而,当我问他们 Spring Boot 最核心的 3 个注解是什么,令我失望 ...

  3. 精尽Spring Boot源码分析 - 剖析 @SpringBootApplication 注解

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  4. Spring Boot入门(三):使用Scheduled注解实现定时任务

    在程序开发的过程中,经常会使用定时任务来实现一些功能,比如: 系统依赖于外部系统的非核心数据,可以定时同步 系统内部一些非核心数据的统计计算,可以定时计算 系统内部的一些接口,需要间隔几分钟或者几秒执 ...

  5. 自定义的Spring Boot starter如何设置自动配置注解

    本文首发于个人网站: 在Spring Boot实战之定制自己的starter一文最后提到,触发Spring Boot的配置过程有两种方法: spring.factories:由Spring Boot触 ...

  6. Spring Boot 项目学习 (二) MySql + MyBatis 注解 + 分页控件 配置

    0 引言 本文主要在Spring Boot 基础项目的基础上,添加 Mysql .MyBatis(注解方式)与 分页控件 的配置,用于协助完成数据库操作. 1 创建数据表 这个过程就暂时省略了. 2 ...

  7. Spring Boot @EnableAutoConfiguration和 @Configuration的区别

    Spring Boot @EnableAutoConfiguration和 @Configuration的区别 在Spring Boot中,我们会使用@SpringBootApplication来开启 ...

  8. 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 ...

  9. spring boot: EL和资源 (一般注入说明(二) @Service注解 @Component注解)

    @Service用于标注业务层组件 : 将当前类注册为spring的Bean @Controller用于标注控制层组件(如struts中的action) @Repository用于标注数据访问组件,即 ...

随机推荐

  1. springmvc转springboot过程中访问jsp报Whitelabel Error Page错误

    前言: 虽然springboot内嵌了一个tomcat,但是这个内嵌的tomcat不支持jsp页面,所以需要引入其他包 解决: maven引入以下包即可 <dependency> < ...

  2. Metrics.Net实践(2)在WEB中应用度量

    Gauges 可以画出Http Request执行时间的波形图: actionInfo表示MVC中的Action,即按照action类型来分组 Metric.Context(this.actionIn ...

  3. AngularJS - 下一个大框架

    AngularJS AngularJS是web应用的下一个巨头. AngularJS如果为创建web应用而设计,那它就是HTML的套路了.具有数据绑定, MVW, MVVM, MVC, 依赖注入的声明 ...

  4. Jquery Ajax自定义无刷新提交表单Form

    Jquery的$.ajax方法可以实现ajax调用,要设置url,post,参数等. 如果要提交现有Form需要写很多代码,何不直接将Form的提交直接转移到ajax中呢. 以前的处理方法 如Form ...

  5. CPU字节序

    小端存储:低对低,高对高(低位存储在低地址,高位存储在高地址) 大端存储:低对高,高对低(低位存储在高地址,高位存储在低地址)   小端字节序: x86体系结构,arm指令只支持小端,数据支持大小端 ...

  6. Codeforces Round #540 (Div. 3)题解

    题目链接: https://codeforces.com/contest/1118 A题: 题意: q次查询,给你一个n,要你用1和2来凑出n,1的花费为a,2的花费为b,求花费的最小值. 思路: 我 ...

  7. php中各种hash算法的执行速度比较

    更多内容推荐微信公众号,欢迎关注: PHP中的Hash函数很多,像MD4.MD5.SHA-1.SHA-256.SHA-384.SHA-512等我们比较常见,那么各个哈希的执行速度呢? $algos = ...

  8. JS设计模式——7.工厂模式(示例-RSS阅读器)

    RSS阅读器 由于我们只想跟RSS容器对象打交道,所以用一个工厂来实例化这些内部对象并把它们组装到一个RSS阅读器中. 使用工厂方法在好处在于,我们创建的RSS阅读器类不会与那些成员对象紧密耦合在一起 ...

  9. Hibernate5笔记1--Hibernate简介和第一个程序

    Hibernate简介: Hibernate是一个开放源代码的ORM(对象关系映射)框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库. Hib ...

  10. Oracle 11.2.0.4在线(Online mode)打补丁14084247解决WRH$_ACTIVE_SESSION_HISTORY不会自动切割的问题

      安装了Oracle Database Release 11.2.0.4之后,发现WRH$_ACTIVE_SESSION_HISTORY始终不会自动分割删除,   后来才发现需要应用补丁:14084 ...