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. nginx.conf 基础配置

    ### 全局块开始### #配置允许运行nginx服务器的用户和用户组 user nobody; #配置允许nginx进程生成的worker process 数 worker_processes 1; ...

  2. Hadoop2.6.0在CentOS 7中的集群搭建

    我这边给出我的集群环境是由一台主节点master和三台从节点slave组成: master     192.168.1.2 slave1       192.168.1.3 slave2       ...

  3. [洛谷P1228]地毯填补问题 题解(分治)

    Description 相传在一个古老的阿拉伯国家里,有一座宫殿.宫殿里有个四四方方的格子迷宫,国王选择驸马的方法非常特殊,也非常简单:公主就站在其中一个方格子上,只要谁能用地毯将除公主站立的地方外的 ...

  4. Caffe的loss layer(转)

    英文可查:地址 1.SoftmaxWithLoss 对一对多的分类任务计算多项逻辑斯蒂损失,并通过softmax传递预测值,来获得各类的概率分布.该层可以分解为SoftmaxLayer+Multino ...

  5. python初步学习-python 模块之 json

    json 模块 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写.一般API返回的数据大多是 JSON.XML,如果返回JSON的话,将获取 ...

  6. 关于limit_req和limit_conn的区别

    1,首先,limit_req和limit_conn两个模块都是为了来限流的,但是两者不在一个层面,为了搞清楚这个,必须先要弄清楚request和connection的区别,因为在很多情况下,我们把他们 ...

  7. Shell编写8点建议

    这八个建议,来源于键者几年来编写 shell 脚本的一些经验和教训.事实上开始写的时候还不止这几条,后来思索再三,去掉几条无关痛痒的,最后剩下八条.毫不夸张地说,每条都是精挑细选的,虽然有几点算是老生 ...

  8. C# 应用程序配置文件App.Config和web.config

    应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本 ...

  9. J2V8 For Android

    J2V8是基于Google的JavaScript引擎V8的Java开源项目,实现Java和JavaScript的相互调用.并对Android平台提供支持,最新版本提供了aar格式的类库包方便Andro ...

  10. 【小程序开发】购物车加减几件demo

    <!-- 主容器 --> <view class="stepper"> <!-- 减号 --> <text class="{{m ...