如何在非Spring管理的普通类中获取注入的Bean值
解决非Spring管理类获取配置的问题
@Value注解仅对Spring容器托管的Bean生效,你手动通过new MyObj()创建的对象不在Spring管理范围内,因此无法自动注入配置。以下是两种实用的解决方案:
方案1:通过Spring上下文直接获取配置,手动传入对象
步骤1:创建Spring上下文持有者
先写一个工具类让Spring帮我们持有上下文,方便后续调用:
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) { SpringContextHolder.applicationContext = context; } public static ApplicationContext getApplicationContext() { return applicationContext; } }
步骤2:修改MyObj类,支持手动传入配置
给MyObj添加构造方法或setter,用来接收配置值:
class MyObj { private int applePrice; // 通过构造方法传入配置 public MyObj(int applePrice) { this.applePrice = applePrice; } // 或者用setter方法 public void setApplePrice(int applePrice) { this.applePrice = applePrice; } // 业务方法中直接使用配置值 public void printPrice() { System.out.println("苹果价格:" + applePrice); } }
步骤3:创建MyObj时传入配置
在你需要创建MyObj的地方,先从Spring上下文获取配置值,再手动传入:
// 从环境变量中获取配置,指定类型为Integer避免类型转换 Integer applePrice = SpringContextHolder.getApplicationContext() .getEnvironment() .getProperty("apple.price", Integer.class); // 初始化MyObj并传入配置 MyObj obj = new MyObj(applePrice); obj.printPrice();
方案2:封装配置类,通过Bean传递配置(适合多配置项场景)
如果你的配置项较多,推荐把配置封装成一个Spring管理的Bean,再传递给MyObj。
步骤1:创建配置类绑定属性
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "apple") public class AppleConfig { private int price; // getter和setter public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
步骤2:获取配置Bean并传入MyObj
// 从Spring上下文获取配置Bean AppleConfig appleConfig = SpringContextHolder.getApplicationContext() .getBean(AppleConfig.class); // 初始化MyObj MyObj obj = new MyObj(appleConfig.getPrice());
注意事项
- 确保
SpringContextHolder所在的包被SpringBoot的组件扫描覆盖(默认扫描启动类所在包及子包)。 - 避免在Spring容器未完全初始化时调用
SpringContextHolder,否则会出现空指针异常。
内容的提问来源于stack exchange,提问作者Yves
相关产品推荐
相关产品推荐

