【问题标题】:Spring not injecting @Value from Properties file in some classesSpring没有在某些类中从属性文件中注入@Value
【发布时间】:2015-08-05 17:53:09
【问题描述】:

在下面的 Spring Boot 应用程序中,@Value 注解在 WebSecurityConfig 类中成功,但在 FileSystemUpload 类中没有。在 FileSystemUpload 类中,值(测试)使用 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

【问题讨论】:

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


    【解决方案1】:

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

    FileSystemUpload upload = new FileSystemUpload()
    

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

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 2011-11-17
      • 2012-09-26
      • 2011-10-31
      • 2021-11-24
      • 2013-04-02
      • 1970-01-01
      • 2017-10-10
      相关资源
      最近更新 更多