我想介绍一些仅在开发过程中执行的方法.
我以为我可以在这里使用Spring @Profile注释?但是,如何在类级别上应用此注释,以便仅在属性中配置特定配置文件时才调用此方法?
spring.profiles.active=dev
将以下内容作为伪代码.如何才能做到这一点?
class MyService { void run() { log(); } @Profile("dev") void log() { //only during dev } }
解决方法
AS可以在
http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/Profile.html上阅读
The @Profile annotation may be used in any of the following ways:
as a type-level annotation on any class directly or indirectly
annotated with @Component,including @Configuration classes as a
meta-annotation,for the purpose of composing custom stereotype
annotations If a @Configuration class is marked with @Profile,all of
the @Bean methods and @Import annotations associated with that class
will be bypassed unless one or more the specified profiles are active.
This is very similar to the behavior in Spring XML: if the profile
attribute of the beans element is supplied e.g.,the beans element will not be parsed unless profiles
‘p1’ and/or ‘p2’ have been activated. Likewise,if a @Component or
@Configuration class is marked with @Profile({“p1”,“p2”}),that class
will not be registered/processed unless profiles ‘p1’ and/or ‘p2’ have
been activated.
所以,一个@Profile注释在一个类,所有的方法和导入.不上课
你想要做的事情可能是通过使两个类实现相同的接口,并根据配置文件注入一个或另一个类来实现的.看看这个问题的答案.
Annotation-driven dependency injection which handles different environments