@Value 注解获取为空,@PostConstruct注解使用

老是忘记,就做个记录

@Value

  • @Value不能和 staticfinal 搭配使用
@Value("${XXX.XXX}")
public static String xxx;  // 错误
@Value("${XXX.AAA}")
public finalString xxx; // 错误
  • 类没有加上@Component(或者@service等)
  • 类被new新建了实例,而没有使用@Autowired

@PostConstruct

这个不是spring的注解,是java自己的
@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
举例:

    @Autowired
    private Environment env;

    private String ecUrl;

    @PostConstruct
    public void init(){
        ecUrl = env.getProperty("ec.url");
    }
posted @ 2022-03-23 16:24  SurfingCat  阅读(874)  评论(0编辑  收藏  举报