Spring Boot 核心注解之 @Configuration注解,@Component注解

 2022-08-13
原文地址:https://cloud.tencent.com/developer/article/1139063

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注解也可以正常运行。