0.问题描述
希望对一个被static修饰的变量使用@Resource赋值
在该类的静态方法中,会调用recipeMapper的方法
但在真正使用时,却报出NPE,提示recipeMapper尚未被赋值
1.解决方案
将原来的代码改成如下格式:
@Resource
private RecipeMapper tempRecipeMapper;
private static RecipeMapper recipeMapper;
@PostConstruct
public void beforeInit(){
//该方法会在这个对象被初始化之前执行
recipeMapper = tempRecipeMapper;
}
1.1.@PostConstruct注解
被该注解修饰的方法会在服务器加载servlet的时候执行,
并且有且只会被服务器执行这一次。
执行顺序为:
构造方法 => @Autowired/@Resource => @PostConstruct
1.2.@Resource注解
@Resource注解属于J2EE,
而@Autowired注解属于Spring,
推荐使用前者
@Resource注解的匹配规则如下:
1) 没有指定name,也没指定type,则先byName匹配,如匹配失败再byType匹配
2) 仅指定name,则byName匹配,匹配失败则抛出异常
3) 仅指定type,则byType匹配,匹配失败则抛出异常