Search code examples
springmultithreadingspring-bootthreadpoolapplication.properties

I can't get value from application.properties in spring boot in any way


I've tried using ways.

@Value("${app.host})
@AutoWired
Environment environment

I can get value from the application.properties in other files, but when I try to get it from thread task where I've implemented Callable Interface, I'm getting value null.

Here my application.properties

app.host = "xyz.com"

Service

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<FTPClient> result = executorService.submit(new FtpConnector());

FtpConnector.java


import java.util.concurrent.Callable;

@Service
@PropertySource("classpath:application.properties")
public class FtpConnector implements Callable<FTPClient>{

    FTPClient ftpClient = new FTPClient();
    Logger logger = LoggerFactory.getLogger(FtpConnector.class);

    @Autowired
    FtpClient client;

    @Value("${app.host}")
    private String host;

    @Override
    public FTPClient call() throws Exception {
        logger.info("Host from connecter {}",host);
}

output

2022-03-02 20:44:03.831  INFO 15135 --- [ool-13-thread-1] t.a.tech.ftpnew.service.FtpConnector     : Host from connecter null

Does anyone have any idea or solution to get values of application.properties in thread. ?


Solution

  • When you use new FtpConnector() it will not do any dependency injection thus FtpClient and host will not be injected. Do the following;

    @Autowired
    private FtpConnector ftpConnector;
    
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<FTPClient> result = executorService.submit(ftpConnector);