素材牛VIP会员
@Autowired @Resource 之类的注解和初始化块哪个先执行?
 麦***j  分类:Java代码  人气:1114  回帖:8  发布于6年前 收藏

如下代码,出错了

public class MyController{
  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  SetOperations<String, String> setOperations;
  HashOperations<String, String, String> hashOperations;

  {
    setOperations = redisTemplate.opsForSet();
    hashOperations = redisTemplate.opsForHash();
  }

是不是注解没有初始化块先执行? 这种状况如何改?

 标签:springredisjava

讨论这个帖子(8)垃圾回帖将一律封号处理……

Lv5 码农
lo***ge 其它 6年前#1

什么错呢? ‘Could not autowire xxx bean’ 错么? 还是NPE(空指针异常,redisTemplate 初始化);

MyController 是 action bean吗 还是刚好有个 工具 叫做xxxController?
若为action bean (springmvc - C),有没有让spring 管理起来?

是springboot 中吗,注解加对了没有?
是ssm中(springmvc.xml 中扫包扫到没有)?

Lv6 码匠
su***in 技术总监 6年前#2

Spring在注入时,首先初始化类,然后根据@Autowired之类的注解进行注入。

@PostConstruct
public void init(){
    setOperations = redisTemplate.opsForSet();
    hashOperations = redisTemplate.opsForHash();
}

使用@PostConstruct注解。

Lv5 码农
最***哥 JS工程师 6年前#3

初始化块儿先执行然后再把对应的属性注入,所以你这里不能这样写你可以采用构造函数注入的方式试试

Lv2 入门
雷***习 技术总监 6年前#4

初始化优先级比较高,仅次于静态
这里可以使用PostConstruct注解,顺序上
Constructor >> @Autowired >> @PostConstruct

Lv6 码匠
zc***78 软件测试工程师 6年前#5

你得把报错信息贴上来。

Lv5 码农
走***鹿 移动开发工程师 6年前#6

肯定是先初始化的,然后再完成注入的一系列操作

Lv4 码徒
L***灬 软件测试工程师 6年前#7

建议看下《Java编程思想》中的初始化顺序相关内容。肯定是先初始化,再注入了。如果初始化都没完成,注入对象到哪里去呢?

Lv5 码农
mi***02 学生 6年前#8
private RedisTemplate<String, String> redisTemplate;
@Autowired

http://blog.csdn.net/ruangong...

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取