[英]Spring beans creation with different annotations
我有一個這樣的bean配置:
@Bean(NAME)
@ConfigurationProperties(PROPS)
public SomeBean getSomeBean(@Qualifier(QUALIFIER) X x) {
return new SomeBean(x);
}
並且有很多類具有相同的配置,但不同的常量(NAME、PROPS、QUALIFIER)。 我考慮過從構造函數(初始化常量字段)或重寫方法傳遞它們,但它不起作用,因為注釋只需要常量。
有什么方法可以創建類似基本 class 的東西並共享這個 bean 初始化,只傳遞特定的常量?
為了提高可重用性並減少開發工作量,Spring 支持 bean 定義 inheritance。
下面的示例代碼解釋了該過程。 在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);
}
}
在主class運行寫
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.