spring注入相关知识

1、@Autowired可以用在controller,service中,但是不可以用在实体model中,用在实体中会出现空指针异常
2、实体中,过滤器中使用注入,可以通过上下文关系获取实体注入,也可以通过@Configuration @Bean注入方法,推荐使用通过上下文获取。
上下文获取实体注入代码如下

@Component
public class application implements ApplicationContextAware {

    private static ApplicationContext Application_Context;

    /**
     * 获取上下文
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Application_Context=applicationContext;
    }

    /**
     * 根据类名注入实体对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        return Application_Context.getBean(beanName);
    }

    /**
     * 根据类返回实体对象
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBeanByClass(Class<T>  beanName ){
        return Application_Context.getBean(beanName);
    }
}

实体类Test

 public class Test {
        private String name;
        /*private static  TestService test_Service=(TestService)application.getBean("TestService");*/
        private static  TestService test_Service=(TestService)application.getBeanByClass(TestService.class);
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        
    
        public static void  cs(){
           test_Service.test();
       }
    }

实体类通过过@Configuration @Bean注入方法,这样就可以将TestService 交给spring容器管理,不能直接new TestService()对象调用,这样会造成service里面自动注入的实体为空。

@Configuration
public class Test {
    private String name;
    private static  TestService test_Service;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Bean
    public static TestService setTestService() {
        Test.test_Service = new TestService();
        return test_Service;
    }

    public static void  cs(){
       test_Service.test();
   }
}

service代码

@Service
public class TestService {

    @Autowired
    private TestService1 service1;

    public  void test(){
        service1.test();
        System.out.println("TestService test()");
    }
}

@Service
public class TestService1 {

    public  void test(){
        System.out.println("TestService1 test1()");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值