如何使用相同的 class 声明多个对象,但在 spring 引导中使用不同的属性
How to declare multiple object with same class but using different properties in spring boot
我想在 Spring 引导注释中使用相同的 class 但不同的属性声明多个对象
application.properties
test1.name=Ken
test2.name=Anthony
代码示例
@Component
public class People {
private String name;
public String getName() {
return this.name;
}
}
@SpringBootApplication
public class Application {
@AutoWired
public People man1;
@AutoWired
public People man2;
System.out.println(man1.getName());
System.out.println(man2.getName());
}
我尝试在声明 man1
之前添加 @ConfigurationProperties(prefix="test1")
但它返回了
The annotation @ConfigurationProperties is disallowed for this location
@ConfigurationProperties
只允许放在 @Configuration
class 或 class 级别的 @Bean
方法上。对于前一种情况,它将属性从 application.properties
映射到 bean 实例,这意味着您必须:
@SpringBootApplication
public class Application {
@Bean
@ConfigurationProperties(prefix="test1")
public People man1() {
return new People();
}
@Bean
@ConfigurationProperties(prefix="test2")
public People man2() {
return new People();
}
}
并且由于 man1
和 man2
是同一类型,您必须进一步使用 @Qualifier
来告诉 Spring 您实际想要通过指定注入哪个实例它的豆名。 bean名称可以通过@Bean("someBeanName")
配置。如果使用@Bean
,没有配置bean名,则使用方法名作为bean名。 (即 man1
和 man2
)
@Autowired
@Qualifier("man1")
public People man1;
@Autowired
@Qualifier("man2")
public People man2;
我想在 Spring 引导注释中使用相同的 class 但不同的属性声明多个对象
application.properties
test1.name=Ken
test2.name=Anthony
代码示例
@Component
public class People {
private String name;
public String getName() {
return this.name;
}
}
@SpringBootApplication
public class Application {
@AutoWired
public People man1;
@AutoWired
public People man2;
System.out.println(man1.getName());
System.out.println(man2.getName());
}
我尝试在声明 man1
之前添加@ConfigurationProperties(prefix="test1")
但它返回了
The annotation @ConfigurationProperties is disallowed for this location
@ConfigurationProperties
只允许放在 @Configuration
class 或 class 级别的 @Bean
方法上。对于前一种情况,它将属性从 application.properties
映射到 bean 实例,这意味着您必须:
@SpringBootApplication
public class Application {
@Bean
@ConfigurationProperties(prefix="test1")
public People man1() {
return new People();
}
@Bean
@ConfigurationProperties(prefix="test2")
public People man2() {
return new People();
}
}
并且由于 man1
和 man2
是同一类型,您必须进一步使用 @Qualifier
来告诉 Spring 您实际想要通过指定注入哪个实例它的豆名。 bean名称可以通过@Bean("someBeanName")
配置。如果使用@Bean
,没有配置bean名,则使用方法名作为bean名。 (即 man1
和 man2
)
@Autowired
@Qualifier("man1")
public People man1;
@Autowired
@Qualifier("man2")
public People man2;