bean实例与init方法 r囧r小猫 2022-05-15 02:44 161阅读 0赞 最近在开发的时候,由于对init方法的调用时机的误解,导致实例初始化时retry字段未未赋值,为0,直接造成线上某接口在调用其他服务失败时重试机制失效而导致接口超时,还好没有酿成大祸。本人也是吓出一身冷汗。所以此次些这边文章的目的也是为了归纳总结开发中的知识盲点,分享给大家,希望小伙伴们能引以为鉴。 我的误区是实例初始化后会自动调用init方法,但是在java中并没有规定在调用了构造方法后会自动调用init方法,是我没有记忆牢固,把知识混淆了。其实这个功能是有spring框架的@Bean注解提供的,在使用@Bean注解时配置initMethod属性为init即可(我使用了@Bean,但是没有初始化initMethod值,悲剧-\_-!),那么下面我用一个例子来演示下该情况。 **PS:@Bean可以用在方法上,但不能用在类上** @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Bean { @AliasFor("name") String[] value() default {}; @AliasFor("value") String[] name() default {}; Autowire autowire() default Autowire.NO; String initMethod() default ""; String destroyMethod() default "(inferred)"; } 不多说,上代码 package com.zbj.demo.entity; public class Person { private String name; private int age; public void init(){ System.out.println("execute method init."); } public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } package com.zbj.demo; import com.zbj.demo.entity.Person; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class DemoApplication { @Bean(initMethod = "init") public Person createPersion() { return new Person("jiafeng", 25); } public static void main(String[] args) { ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args); System.out.println(appContext.getBean("createPersion")); } } 结果如下: ![result.png][] @Bean的用法已经明白了,可能有人有新的疑惑,@Component @Controller @Service @Repository 这几个注解同样能往spring容器中添加bean,那是否也拥有自动调用init的功能呢,查看注解源码,并没有类似于initMethod的属性,所以并不能。如果还想知道@Bean与这几个注解的区别,[可以参考这篇博文][Link 1]。 [result.png]: https://app.yinxiang.com/shard/s9/res/53923166-9666-4b8c-a1f9-3786ebcdb7c1/result.png [Link 1]: https://blog.csdn.net/qq_28411869/article/details/81983576
还没有评论,来说两句吧...