Eclipse中Spring @Autowired的FindBugs null问题



我正在使用findbugs Eclipse插件(3.0.1.20150306-5afe4d1), spring (4.2.2.RELEASE)和Eclipse(火星1(4.5.1))一起,我在Eclipse中收到以下findbugs错误。

非空字段env未被new org.test.app.config.AppConfiguration()初始化[吓人(8),正态置信度]

我正在使用使用默认构造函数和使用自动装配来初始化env变量。我也有一个PostConstruct注释被调用后,一切都连接和访问env变量,以确保它被正确初始化。

我怎么能使这个错误消失而不关闭FindBugs插件,仍然使用@Autowired注释?

package org.test.app.config;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@ComponentScan(basePackages = { "org.test.app" })
@PropertySource("classpath:/${spring.profiles.active:local}.properties")
public class AppConfiguration {
    private static final Logger log = LoggerFactory.getLogger(AppConfiguration.class);
    @Autowired
    private Environment env;
    /**
     * Dump profile info.
     */
    @PostConstruct
    public void details() {
        log.debug("** App application context, active profile(s)={}", Arrays.toString(env.getActiveProfiles()));
    }
}

我尝试使用构造函数每个@spoonybard896的建议,但它没有工作。我收到以下错误:

java.lang.NoSuchMethodException: org.test.app.config. AppConfiguration $$EnhancerBySpringCGLIB$$cbece1d7.<init>()
[STDOUT] at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_60]
[STDOUT] at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_60]
[STDOUT] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiat‌​e(SimpleInstantiationStrategy.java:80) ~[na:na]

使用非默认构造函数如何?

private final Environment env;
@Autowired
public AppConfiguration(final Environment env) {
    this.env = env;
}

编辑

上述方法适用于@Controller实例,但不适用于@Configuration。在做了一些快速的研究之后,结果是:

@Configuration使用@Component进行元注释,因此@Configuration类是组件扫描的候选类(通常使用Spring XML的<context:component-scan/>元素),因此也可以在字段和方法级别(但不是在构造函数级别)利用@Autowired/@Inject

我认为,除非有某种类型的插件FindBugs理解Spring注释(我不知道一个),然后你可能只需要应用一个过滤器FindBugs插件,并让它忽略特定文件中的特定错误(或在任何配置类一般)。在Eclipse中,查看Preferences -> Java -> Findbugs -> Filter Files,并查看描述类似问题和解决方案的链接,但要确保只过滤掉您想要的错误。我们的目标不是关闭FindBugs,而是让它忽略这一种情况。

编辑2

在类中添加注释将只抑制此文件的FindBugs错误。

@SuppressFBWarnings(
    value="NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR",
    justification="Overriding the check on the env variable because Spring will automatically initialize the variable after the constructor is called and before any public methods are called.")

最新更新