静态 方法中使用Autowired注解的service或dao的问题
2017-08-12 17:09
861 查看
0 @Component //此处注解不能省却(0) 1 public class NtClient { 2 /** 3 * 日志 4 */ 5 private static String clazzName = NtClient.class.getName(); 6 /** 7 * 此处是要使用的service需要spring注入(1) 8 */ 9 @Autowired 10 private NotifyTimeService notifyTimeService; 11 private static NtClient ntClient; 12 /** 13 * 注意此处注解(2) */ 14 @PostConstruct 15 public void init() { 16 ntClient = this; 17 ntClient.notifyTimeService = this.notifyTimeService; 18 } 19 /** 20 * 主要使用场景(3) 21 */ 22 public static void insertParam(int id){ 23 /** 24 * 注意此处的调用方法(4) 25 */ 26 if(ntClient.notifyTimeService.deleteNotifyTime(id)){ 27 } 28 } 29 } 注释:(0)处作用是将(2)ntClient = this;this进行赋值(注:如果无注解ntClient 将null)(1)处为spring自动注入,使用spring框架的很常用,但是如果在静态方法中调用此注入类的方法,发现注入为'null';原因不是spring未注入,而是被static方法给'清空'了,在无法先于static方法初始化之前想了一个办法 (2)处为想到的办法:通过(注:@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。PreDestroy()方法在destroy()方法执行执行之后执行)的方法public void init()先给该类赋值,然后通过(1)出注入进来。这样不影响dao等service下面调用的注入! (3)处要处理的特殊方法static(经典是 main()方法,自己想想基础,它里面可以使用的方法调用的模式) (4)处是使用这样模式的调用方式notifyTimeService现在是作为ntClient的属性
相关文章推荐
- 静态方法使用@Autowired注解报null问题
- @webservice 注解的类中使用@Autowired 进行bean注入,注入的bean调用时为空的问题
- 解决 SpringMvc 非controller类使用@Autowired注解 service注入为null的问题
- 使用spring的@autowired注解,无法实例化dao,service,controller等
- 工作中问题记录--servlet中使用@Autowired注解
- 静态工具类中使用注解注入service(静态方法调用有注解的非静态方法)
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(三):通过 @Autowired的使用来消除 set ,get方法。
- servlet中利用spring的注解@Autowired自动注入service失败,优雅的解决方法
- @Autowired注解和静态方法
- @Autowired注解和静态方法
- 使用Spring的@Autowired 实现DAO, Service, Controller三层的注入
- Spring @Autowired @Resource @Inject 注解使用方法及区别总结
- 使用Spring的@Autowired 实现DAO, Service, Controller三层的注入(转)
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(三):通过 @Autowired的使用来消除 set ,get方法。
- 解决非controller使用@Autowired注解注入为null问题
- 解决非controller使用@Autowired注解注入为null问题
- SSM SpringMVC 非Controller类使用@Autowired注解Service为null的解决办法
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(三):通过 @Autowired的使用来消除 set ,get方法。
- 工作中问题记录--servlet中使用@Autowired注解
- @Autowired注解和静态方法 NoClassDefFoundError could not initialize class 静态类