【问题标题】:Spring beans creation with different annotations使用不同注释创建 Spring bean
【发布时间】:2021-04-13 06:56:21
【问题描述】:
我有一个这样的 bean 配置:
@Bean(NAME)
@ConfigurationProperties(PROPS)
public SomeBean getSomeBean(@Qualifier(QUALIFIER) X x) {
return new SomeBean(x);
}
而且有很多类具有相同的配置,但不同的常量(NAME、PROPS、QUALIFIER)。我考虑过从构造函数(初始化常量字段)或重写方法传递它们,但它不起作用,因为注释只需要常量。
有什么方法可以创建类似基类的东西并共享这个 bean 初始化,只传递特定的常量?
【问题讨论】:
标签:
java
spring
annotations
initialization
javabeans
【解决方案1】:
为了提高可重用性并尽量减少开发工作,Spring 支持 bean 定义继承。
下面的示例代码解释了这个过程。在java配置文件中写入
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public Employee employee() {
Employee employee = new Employee();
initCompany(employee);
employee.setLocation("XYZ");
return employee;
}
private void initCompany(Company company) {
company.setName("abc");
company.setAge(30);
}
}
在主类中运行write
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
Employee employee = ctx.getBean(Employee.class);
System.out.println(employee.getName());
System.out.println(employee.getLocation());
System.out.println(employee.getAge());
ctx.registerShutdownHook();
}
}
Output
abc
XYZ
30