方法级别的Spring配置文件? [英] Spring Profiles on method level?

查看:116
本文介绍了方法级别的Spring配置文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想介绍一些仅在开发过程中执行的方法。

I'd like to introduce some methods that are only executed during development.

我以为我可能会使用 Spring @Profile 注释在这里?但是如何在类级别上应用此批注,以便仅在属性中配置特定的配置文件时才调用此方法?

I thought I might use Spring @Profile annotation here? But how can I apply this annotation on class level, so that this method is only invoked if the specific profile is configured in properties?

spring.profiles.active=dev

将以下内容作为伪代码。怎么办呢?

Take the following as pseudocode. How can this be done?

class MyService {

    void run() { 
       log();
    }

    @Profile("dev")
    void log() {
       //only during dev
    }
}


推荐答案

您可以阅读 http://docs.spring.io/spring/ docs / 3.1.x / javadoc-api / org / springframework / context / annotation / Profile.html


@Profile注释可以通过以下任何一种方式使用:

The @Profile annotation may be used in any of the following ways:

作为任何类的类型级注释直接或间接
使用@Component注释,包括@Configuration类作为
元注释,用于组成自定义构造型
注释如果@Configuration类标记为@Profile,则所有
@Bean方法和@Import除非一个或多个指定的专业版,否则将绕过与该类
相关联的注释文件是活动的。

这与Spring XML中的行为非常相似:如果提供了beans元素的profile
属性,例如,除非profiles $,否则将不会解析beans元素b $ b'p1'和/或'p2'已被激活。同样,如果使用@Profile({p1,p2})标记@Component或
@Configuration类,则除非配置文件'p1'和/,否则将不会注册/处理该类
或'p2'已激活

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注释适用于所有类方法和进口。不要上课。

So, a @Profile annotation on a class, aplies to all of it's methods and imports. Not to the class.

你要做的事情可能是通过让两个类实现相同的接口,并根据配置文件注入一个或另一个来实现的。 。看看这个问题的答案。

What you're trying to do could probably be achieved by having two classes that implement the same interface, and injecting one or another depending on the profile. Take a look at the answer to this question.

注释驱动依赖注入,处理不同的环境

这篇关于方法级别的Spring配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆