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. R8—批量生成文件夹,批量读取文件夹名称+R文件管理系统操作函数

    一. 批量生成文件夹,批量读取文件夹名称 今日,工作中遇到这样一个问题:boss给我们提供了200多家公司的ID代码(如6007.7920等),需要根据这些ID号去搜索下载新闻,从而将下载到的新闻存到 ...

  2. 【leetcode 简单】 第六十九题 删除链表中的节点

    请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点. 现有一个链表 -- head = [4,5,1,9],它可以表示为: 4 -> 5 -> 1 - ...

  3. 浏览器断点调试js

    说了一些 Chrome 开发者工具的技巧,其实并没有涉及到开发者工具最核心的功能之一:断点调试.断点可以让程序运行到某一行的时候,把程序的整个运行状态进行冻结.你可以清晰地看到到这一行的所有的作用域变 ...

  4. 20165230 2017-2018-2 《Java程序设计》第9周学习总结

    20165230 2017-2018-2 <Java程序设计>第9周学习总结 教材学习内容总结 第十二章 java网络编程 学习了用于网络编程的类,了解URL.Socket.InetAdd ...

  5. 安裝HA服務

    **************************************************************************************************** ...

  6. Gh0st配置加密与解密算法(异或、Base64)

    1.前言 分析木马程序常常遇到很多配置信息被加密的情况,虽然现在都不直接分析而是通过Wireshark之类的直接读记录. 2017年Gh0st样本大量新增,通过对木马源码的分析还发现有利用Gh0st加 ...

  7. Vim 快捷键整理【转】

    转自:http://blog.csdn.net/ceven2010/article/details/7406341 一.移动光标 1.左移h.右移l.下移j.上移k 2.向下翻页ctrl + f,向上 ...

  8. ActiveMQ 使用场景

    ActiveMQ 安装测试就不做介绍了,下面我说说ActiveMQ 使用场景.(松耦合与ActiveMQ) 1.非均匀应用集成 ActiveMQ 中间件用Java语言编写,因此自然提供Java客户端 ...

  9. hibernate的枚举注解@Enumerated

    @Enumerated(value=EnumType.ORDINAL)采用枚举类型的序号值与数据库进行交互, 此时数据库的数据类型需要是数值类型,例如在实际操作中 CatTest ct = new C ...

  10. elasticsearch5.5

    1.不能以root用户运行 groupadd es          #增加es组 useradd es -g es -p pwd          #增加es用户并附加到es组 chown -R e ...