zoukankan      html  css  js  c++  java
  • Spring boot 梳理

    1. 直接注入(Autowired)
      1. @Configuration
        public class OAConfig {
            @Autowired
            private ApplicationContext applicationContext;
            
            @Bean
            public PersonUtils personUtil(){
                boolean bool=applicationContext.containsBean("aa");
                System.out.println("containsBean:aa:"+bool);
                return new PersonUtils();
            }
        }
        
        
        
        @Component
        public class User {
        
            @Autowired
            private ApplicationContext applicationContext;
        }
    2. 构造器方法注入
      1. @Component
        public class User{
            private ApplicationContext applicationContext;
        
            public User(ApplicationContext applicationContext) {
                this.applicationContext = applicationContext;
            }
        }
    3. 手动构建类实现接口
      1. /**
         * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
         *
         * @author yj
         * @date 2018年5月27日 下午6:32:11
         */
        @Component
        public class SpringContextHolder implements ApplicationContextAware {
        
            private static ApplicationContext applicationContext;
        
            @Override
            public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
                SpringContextHolder.applicationContext = applicationContext;
            }
        
            public static ApplicationContext getApplicationContext() {
                assertApplicationContext();
                return applicationContext;
            }
        
            @SuppressWarnings("unchecked")
            public static <T> T getBean(String beanName) {
                assertApplicationContext();
                return (T) applicationContext.getBean(beanName);
            }
        
            public static <T> T getBean(Class<T> requiredType) {
                assertApplicationContext();
                return applicationContext.getBean(requiredType);
            }
        
            private static void assertApplicationContext() {
                if (SpringContextHolder.applicationContext == null) {
                    throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
                }
            }
        
        }
  • 相关阅读:
    产品开源了(discuz!nt 2.0),顺便将前些时候发的文章做个总结
    一个曾经的"愤青梦"弥衡
    推荐两个web菜单控件(右击和顶部主菜单)
    一本晚看了两年半的书蓝海战略
    Discuz!NT 在线用户功能简介
    我的2007
    ajax.net调用session和cookie
    最新(2010年)搜索引擎优化(SEO)专家工具集合
    Android学习资料大全
    基于.net的aop实现技术
  • 原文地址:https://www.cnblogs.com/jiangtao1218/p/10187752.html
Copyright © 2011-2022 走看看