I have the need of enable/disable a @Aspect on a class in a Spring (non boot) application.
Spring version is: 4.1.6.RELEASE
I have a .properties file ( that we already use successfully in other point of the application, for example to select the log4j2 configuration file ) with the property aspect.enabled=true|false
and I tried using the @ConditionalOnExpression
annotation to enable|disable it.
This is my try:
application.properties file:
aspect.enabled=true
Class code:
@Configuration
@PropertySource(ignoreResourceNotFound = true, value = { "file:${catalina.home}/conf/application.properties" })
@ConditionalOnExpression("'${aspect.enabled}'=='true'")
@Aspect
@Component
public class TimingProfilerProduction {
@Value("${aspect.enabled}")
public String aspect;
With this configuration the expression is always evaluated to false .
I tried putting a single "true" to see if it works in this simple way:
@Configuration
@PropertySource(ignoreResourceNotFound = true, value = { "file:${catalina.home}/conf/application.properties" })
@ConditionalOnExpression("true")
@Aspect
@Component
public class TimingProfilerProduction {
@Value("${aspect.enabled}")
public String aspect;
Of course in this way the @ConditionalOnExpression gets evaluated to true and I can also prove that the aspect class property correctly reads the aspect.enabled property.
Try #3
I tried with a @ConditionalOnProperty :
@Configuration
@PropertySource(ignoreResourceNotFound = true, value = { "file:${catalina.home}/conf/application.properties" })
@ConditionalOnProperty(prefix="aspect", name="enabled", havingValue = "true")
but nothing, always false .
Try #4:
@ConditionalOnExpression("${aspect.enabled}")
or
@ConditionalOnExpression("!${aspect.enabled}")
Gives an error:
Caused by: org.springframework.expression.spel.SpelParseException: EL1041E:(pos 1): After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
Try #5 (with default values):
@ConditionalOnExpression("${aspect.enabled:true}")
always gives true (even with aspect.enabled=false
), and accordingly
@ConditionalOnExpression("${aspect.enabled:false}")
always gives false
Instead of:
@ConditionalOnExpression("'${aspect.enabled}' == 'true'")
Try:
@ConditionalOnExpression("${aspect.enabled} == true")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.