java - 使用 new 关键字创建对象时如何调用 PostConstruct 方法
问题描述
我有一个类Banana
,它有一个@PostConstruct
我想在创建类对象后运行的方法。我正在使用这些调用创建此类的对象
Cat cat = new Cat();
Banana b = new Banana(cat);
因此,从日志中我了解到,在创建对象@PostConstruct
时不会调用此方法。Banana
我认为我实施的方式不是正确的用法。有人可以指导我如何正确实现这一点,因为这是我使用 Spring Boot 进行 Java 项目的第一个任务。我需要在Banana
创建对象后运行该设置代码,所以除了@PostConstruct
@Slf4j
public class Banana {
public Banana(Cat cat) {
this.cat = cat;
}
private Cat cat;
@PostConstruct
public void setup() {
// some code
}
public void execute() {
// some code
}
}
解决方案
当对象由 spring 本身创建时,spring支持的所有注释(@PostConstruct
、和许多其他注释)都适用。在这种情况下,spring 可以分析类、处理注释等。@PreDestroy
@Autowired
当你自己实例化时(new Banana()
)——spring 甚至不知道你的对象存在,因此不能调用它的任何方法,所以你被迫自己做。所以是的,在这种情况下,您将不得不@PostConstruct
手动调用带有注释的方法,这意味着@PostConstruct
注释非常无用,可以完全省略。
推荐阅读
- workbox - Workbox Precaching 不适用于 / 或 index.php
- javascript - 将带有选择字段的表转换为 js 数组
- javascript - 为什么使用 javascript 将 textarea 切换为只读属性会受到警报提示的影响?
- ms-access - 使用命令按钮以连续形式对文本框进行排序
- javascript - 我需要关于井字游戏的帮助,我无法改变转弯
- java - 如何在从新房间持久性库加载数据时显示加载器并进行失败或成功等回调
- scala - scala - 在方法中定义的 Array("one", "two").mkString(":") 返回 WrappedArray,而不是 String
- angular - 如何使用 agm-circle angular 4 触发更改事件以获取新的半径、纬度和经度
- python - 在 Python 中,如何将字符串与字典项匹配(如 'Bra*')
- database - 在 mule 中获取 oracle spring bean 配置的 NoSuchBeanDefinitionException 错误