Spring不会在某些类中从Properties文件中注入@Value

时间:2015-08-05 17:53:09

标签: java spring spring-mvc dependency-injection spring-boot

在下面的Spring Boot应用程序中,@ Value注释在WebSecurityConfig类中成功,但在FileSystemUpload类中没有。在FileSystemUpload类中,值(testing)使用WebSecurityConfig正在使用的相同属性文件生成null。

Application.java

package com.project;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource("${project.properties}")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

WebSecurityConfig.java(@Value注入正常工作)

package com.project.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private static String ldapUser;
    @Value("${ldap.user: user}")
    public void setPrivateLdapUser(String privateName) {
    ldapUser = privateName;
    }  
    ...
}

FileSystemUpload.java(测试未注入且为空)

package com.project.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FileSystemUpload {

    @Value("${testing}")
    String testing;

    ...
}

utility.properties     测试= thisisatest

1 个答案:

答案 0 :(得分:0)

我自己能够回答这个问题。事实证明,类FileSystemUpload被引用为普通的Java对象:

FileSystemUpload upload = new FileSystemUpload()

应该使用Spring注释来引用类(@Autowired)。一旦我将对类的引用转换为@Autowired并删除了新的FileSystemUpload类的创建,该类中的所有@Value注入都有效。