Within a Spring Component I have a @PostConstruct
statement. Similar to below:
@Singleton
@Component("filelist")
public class FileListService extends BaseService {
private List listOfFiles = new Arrays.list();
//some other functions
@PostConstruct
public void populate () {
for (File f : FileUtils.listFiles(new File(SystemUtils.JAVA_IO_TMPDIR), new String[]{"txt"},true)){
listOfFiles.add(f.getName());
}
}
@Override
public long count() throws DataSourceException {
return listOfFiles.size();
}
// more methods .....
}
During Unit tests I would not like to have the @PostConstruct
function called, is there a way to telling Spring not to do post processing? Or is there a better Annotation for calling a initiation method on a class durning non-testing ?
The method SalesDataAggregate is running on startup because of the @PostConstruct annotation. If you want to keep it from running during tests you can create the class containing the post construct in your test folder and add the @primary annotation so it takes precedence over the class in your main project.
In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.
When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.
Declare a bean to override the existing class and make it Primary.
@Bean
@Primary
public FileListService fileListService() {
return mock(FileListService.class);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With