Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable @PostConstruct in Spring during Test

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 ?

like image 972
Ben Avatar asked Nov 05 '12 11:11

Ben


People also ask

How can Postconstructs be prevented?

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.

Is @PostConstruct deprecated?

In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.

When @PostConstruct is invoked?

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.

Is @PostConstruct Spring annotation?

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.


1 Answers

Declare a bean to override the existing class and make it Primary.

@Bean
@Primary
public FileListService fileListService() {
 return mock(FileListService.class);
}
like image 117
Dilip Tharoor Avatar answered Oct 04 '22 04:10

Dilip Tharoor