Reputation: 5733
I have this component- class and if the property accounting.generalServiceConfig.accountPageSize is in application.properties than a log entry should be written into the log file. But with this class at bottom it does not work. If I add the annotation @Bean at method printAccountPageSize and return e.g. new Object() than it works. Is there a possibility to make it work with the class like it is alt the bottom?
@Component
public class ConditionalPropertyChecker extends AbstractService {
protected final Logger logger = LoggerFactory.getLogger(getClass());
public ConditionalPropertyChecker() {
}
@ConditionalOnProperty(name = "accounting.generalServiceConfig.accountPageSize")
public void printAccountPageSize() {
logger
.info("the accountPageSize is set in application.properties");
}
}
Upvotes: 1
Views: 2792
Reputation: 909
In my case, I have totally different properties filename, it seems like @ConditionalOnProperty can only read properties in the application.properties or application.yml. I tried to add annotation like @PropetySource, still not working.
Once I add for example application.properties in my project, my class (not only bean, but also component, service, etc) can conditionally be initialized perfectly. However,I don't want to add a new properties file (i.e. application.properties) in the project only because of this annotation. If someone has a more decent solution, please comment below:) Otherwise, I have to create the object manually.
Upvotes: 0
Reputation: 51451
@ConditionalOnProperty is for @Configuration classes producing @Bean.
You can do this:
@Component
public class ConditionalPropertyChecker extends AbstractService {
protected final Logger logger = LoggerFactory.getLogger(getClass());
public ConditionalPropertyChecker(@Value("${accounting.generalServiceConfig.accountPageSize}") Integer pageSize) {
if (pageSize) {
logger.info("the accountPageSize is set in application.properties");
}
}
}
Upvotes: 1