When I try to inject the packagePropertiesList
Bean in Operation.class
, I get values from a properties file. But when I use operation.removeStudentFromList()
, I get only null values. Do you see any problem here?
@SpringBootApplication
public class LearningCenterApplication {
public static void main(String[] args) {
SpringApplication.run(LearningCenterApplication.class, args);
ApplicationContext context =
new AnnotationConfigApplicationContext(Config.class, Operations.class, PackageProperties.class);
Operations operations = context.getBean(Operations.class);
operations.removeStudentFromList();
}
@Bean
List<PackageProperties> packagePropertiesList(List<PackageProperties> packageProperties) {
System.out.println(packageProperties);
return packageProperties;
}
@Bean
@ConfigurationProperties(prefix = "remove")
public PackageProperties removeMethod() {
return new PackageProperties();
}
@Bean
@ConfigurationProperties(prefix = "add")
public PackageProperties addMethod() {
return new PackageProperties();
}
}
@Component
public class Operations {
private List<PackageProperties> packagePropertiesList;
@Autowired
public Operations(List<PackageProperties> packagePropertiesList) {
this.packagePropertiesList = packagePropertiesList;
}
public void removeStudentFromList() {
System.out.println(packagePropertiesList);
}
}
public class PackageProperties {
private String packageName;
private String className;
private String methodName;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
@Override
public String toString() {
return packageName "." className "." methodName;
}
}
application.properties
remove.packageName = org.epam.operations
remove.className = Operations
remove.methodName = removeStudentFromList()
add.packageName = org.epam.operations
add.className = Operations
add.methodName = addStudent()
[null.null.null]
— output when operations.removeStudentFromList()
is invoked
CodePudding user response:
You are creating an additional ApplicationContext next to the one that's already created by Spring Boot (with new AnnotationConfigApplicationContext()
. Remove that and use the existing context to get a bean, or rather have a look at the ApplicationRunner
interface, if you want to run code automatically after the application has started.
The whole property handling will only work for the application context, that's created and managed by Spring Boot, not for the one that you created yourself.