常用注解

@PostConstruct和static静态块初始化的区别

@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。

static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException (Your dependencies are null) .

Move your code to a method annotated with @PostConstruct. This will ensure that your code will run when all the dependencies of your component are initialized
译文:static模块会被引入,当class加载后。你的component组件的依赖还没有初始化。这就是为什么你的代码块会报空指针异常。(你的依赖都是null)

 

1,@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,

为此,可以使用@PostConstruct注解一个方法来完成初始化,

@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

2,执行优先级高于非静态的初始化块,它会在类初始化(类加载的初始化阶段)的时候执行一次,执行完成便销毁,它仅能初始化类变量,即static修饰的数据成员。
 

初始化失败:

static {
    strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
   System.out.println("初始化完成" + strategyMap.size());
}

初始化成功:

@PostConstruct
void init() {
    strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
    System.out.println("初始化完成" + strategyMap.size());
);
}

@Async

   在Spring中,基于@Async标注的方法,称之为异步方法;这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。

如何在Spring中启用@Async

      基于Java配置的启用方式:

 @Configuration
 @EnableAsync
 public class SpringAsyncConfig { ... }

基于XML配置文件的启用方式,配置如下:

1 <task:executor id="myexecutor" pool-size="5"  />
2 <task:annotation-driven executor="myexecutor"/>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值