【发布时间】:2018-12-19 21:22:31
【问题描述】:
我在自动装配属性类时遇到问题。
以下是我的属性类,当我在 @service 类中自动装配它时表现良好。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@RefreshScope
public class SMSHistoryProperties {
@Autowired
Environment env;
/**
* Return the property value associated with the given key, or null if the
* key cannot be resolved.
*
* @param propName
* @return
*/
public String getProperty(String propName){
return env.getProperty(propName);
}
但是当我在我的 SQLConstants 类(只有静态常量变量)中自动装配它时,我遇到了一个异常。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.vzw.onem.search.properties.SMSHistoryProperties;
@Component
public class SQLConstants {
@Autowired
private static SMSHistoryProperties prop;
//~ Static fields/initializers ------------------------------------------
private static final String SMS_SCHEMA = prop.getProperty("sms.schema");
我得到的异常如下:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'SQLConstants' defined in file
[...\SQLConstants.class]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.search.constants.SQLConstants]: Constructor
threw exception; nested exception is java.lang.NullPointerException
编辑:
我取出了静态最终引用,但仍然出现空指针异常。
@Autowired
private SMSHistoryProperties prop;
private String BATCH_SMS_SQL = "SELECT ACK_CODE FROM "
+ prop.getProperty("sms.schema");
nullpointer 发生在 prop.getProperty("sms.schema")。
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“SMSController”的 bean 时出错:不满足的依赖关系 通过字段“smsBuilder”表示;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“SMSBuilder”的 bean 时出错:不满足的依赖关系 通过字段“searchHelper”表示;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“smsJdbcSearchHelper”的 bean 时出错:不满意 通过字段 'cccDao' 表达的依赖关系;嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 创建文件中定义的名称为“smsSearchDAOImpl”的bean [..\SmsSearchDAOImpl.class]:bean 实例化失败;嵌套的 例外是 org.springframework.beans.BeanInstantiationException: 无法实例化 [com.vzw.onem.search.dao.impl.SmsSearchDAOImpl]: 构造函数抛出异常;嵌套异常是 java.lang.NullPointerException
【问题讨论】:
-
你能发布更多的堆栈跟踪吗?以及相关代码
-
您最好将自动装配的项目作为构造函数参数提供(更不会出错),在这种情况下,只需使用
@Value("${sms.schema}") String schema作为构造函数参数,而不是手动将其从环境中拉出. -
@chrylis 但是把它从环境中拉出来更理想不是吗?如果您使用 Value 注释来执行此操作,那么您将使用属性注释淹没您的应用程序
-
@Robin 您已经在您的
getProperty调用中使用相同的信息“泛滥”了您的应用程序,您只需将其移得更远并使其难以覆盖(例如,用于测试)。最好明确地公开“bean foo 需要这两个值”,而不是说“bean foo 获取 env 并从中提取一些未指定的信息”。 -
@chrylis 我可能误解了你,你能详细说明一下。如果我坚持使用环境方法,那么我将只需要使用
getProperty(value),而不是使用值注释的字段变量。为什么环境方式不如使用值注释显式调用它理想。
标签: java spring spring-boot