Spring中Bean类内Autowired失效问题:通过Environment注入属性
没问题,我帮你把这个School Bean的实现补全,确保它能正确从mi.properties里读取属性并完成初始化。咱们一步步来:
完整的School Bean实现
首先修正并完善你的School类,这里既支持构造器注入Environment读取属性,也保留了EnvironmentAware接口的实现(如果后续有动态属性需求的话可以用):
import org.springframework.core.env.Environment; import org.springframework.context.EnvironmentAware; public class School implements EnvironmentAware { private String schoolName; private int schoolGrade; private int totalStudents; // 示例属性,可根据需求调整 // 构造器注入Environment,直接读取属性初始化 public School(Environment env) { // 读取mi.name,找不到时用默认值"DefaultSchool" this.schoolName = env.getProperty("mi.name", "DefaultSchool"); // 读取mi.grade并转为int类型,默认值设为10(可自定义) this.schoolGrade = env.getProperty("mi.grade", Integer.class, 10); // 如果totalStudents需要从属性读取,可添加类似逻辑: // this.totalStudents = env.getProperty("mi.totalStudents", Integer.class, 0); this.totalStudents = 0; // 临时默认值 } // EnvironmentAware接口的实现方法(可选,若无需动态更新属性可删除) @Override public void setEnvironment(Environment environment) { // 这里可以做构造器之外的属性初始化,比如动态更新属性 // this.totalStudents = environment.getProperty("mi.totalStudents", Integer.class, 0); } // 可选:添加getter方法用于验证结果 public String getSchoolName() { return schoolName; } public int getSchoolGrade() { return schoolGrade; } public int getTotalStudents() { return totalStudents; } }
配置类:加载属性文件+注册Bean
接下来需要创建一个Spring配置类,告诉Spring加载你的mi.properties文件,并把School类注册为Bean:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @Configuration // 加载类路径下的mi.properties文件,确保文件放在resources目录下 @PropertySource("classpath:mi.properties") public class AppConfig { // 注册School Bean,通过方法参数注入Environment @Bean public School school(Environment env) { return new School(env); } }
关键注意点
- 属性文件路径:确保
mi.properties放在项目的src/main/resources目录下,这样@PropertySource("classpath:mi.properties")才能正确加载它。 - 类型安全读取:用
getProperty(String key, Class<T> targetType, T defaultValue)方法可以直接把字符串属性转为对应类型(比如int),避免手动转换可能出现的异常。 - 构造器注入 vs EnvironmentAware:如果只是初始化时读取属性,构造器注入
Environment就足够了;EnvironmentAware更多用于Bean生命周期中需要动态获取环境属性的场景,你可以根据需求选择是否保留。
测试验证
写个简单的主类验证一下:
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); School school = context.getBean(School.class); System.out.println("学校名称:" + school.getSchoolName()); // 输出GB System.out.println("年级:" + school.getSchoolGrade()); // 输出13 context.close(); } }
内容的提问来源于stack exchange,提问作者Sunil Hegde
相关产品推荐
相关产品推荐

