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用于标注数据访问组件,即 ...
随机推荐
- Metrics.NET实践(1)
起因:对应用的监控和测量是WEB应用的一个重要话题,尤其在监控错误率,并发量,以及框架库中的动态值.于是,在性能优化的时候找到了metrics.net. 简介 开始使用 度量 Gauges Count ...
- Redis实战(一)CentOS 7上搭建redis-3.0.2
1.安装redis wget http://download.redis.io/releases/redis-3.0.2.tar.gz tar zxvf redis-3.0.2.tar.gz cd ...
- MySQL在net中Datatime转换
<add name="adDb" connectionString="Persist Security Info=False;database=ad ...
- [转载]function与感叹号
http://swordair.com/function-and-exclamation-mark/ 最近有空可以让我静下心来看看各种代码,function与感叹号的频繁出现,让我回想起2个月前我回杭 ...
- 谁说码农不懂浪漫?js写的'老婆生日快乐'特效
一直被老婆抱怨不懂浪漫,老婆的生日又来了,老婆指着闺蜜空间上贴的老公做的胡萝卜心形浪漫晚餐告诉我:必须送她一份用心的礼物.我绞尽脑汁想出这么一法子,还是得用我们码农的独特方式,经过一天多的努力,终于做 ...
- pf
here Pro 排列n个不同的数成为长度为p的序列 每两个相同的数之间至少要隔着m个数 求排列总方案数 Input 三个整数 n,m,p output 输出一个数字表示序列组成方法,由于结果可能很大 ...
- 【译】第八篇 SQL Server代理使用外部程序
本篇文章是SQL Server代理系列的第八篇,详细内容请参考原文 在这一系列的上一篇,学习了如何用SQL Server代理作业活动监视器监控作业活动和查看作业历史记录.在实时监控和管理SQL Ser ...
- 南京邮电大学CTF密码学部分Writeup
异性相吸 1.xor 2.hex2binary 3.len(bin(miwen))==len(bin(mingwen)) # -*- coding:utf-8 -*- file_de = open(' ...
- [转]Git忽略提交规则 - .gitignore配置运维总结
在使用Git的过程中,我们喜欢有的文件比如日志,临时文件,编译的中间文件等不要提交到代码仓库,这时就要设置相应的忽略规则,来忽略这些文件的提交.简单来说一个场景:在你使用git add .的时候,遇到 ...
- Nginx常见错误与问题之解决方法技术指南
Nginx常见错误与问题之解决方法技术指南. 安装环境: 系统环境:redhat enterprise 6.5 64bit 1.Nginx 常见启动错误 有的时候初次安装nginx的时候会报这样的 ...