加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 方法级别的Spring配置文件?

发布时间:2020-12-14 14:48:21 所属栏目:Java 来源:网络整理
导读:我想介绍一些仅在开发过程中执行的方法. 我以为我可以在这里使用Spring @Profile注释?但是,如何在类级别上应用此注释,以便仅在属性中配置特定配置文件时才调用此方法? spring.profiles.active=dev 将以下内容作为伪代码.如何才能做到这一点? class MyServ
我想介绍一些仅在开发过程中执行的方法.

我以为我可以在这里使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读