Spring @Value注解注入非静态变量始终返回null该如何解决
问题解决方案
核心错误
MailServiceAuthProvider未被注册为Spring容器托管的Bean:你在类上标注的@ComponentScan仅用于指定Spring的Bean扫描路径,不会将当前类本身注册为Bean。只有Spring托管的Bean才会触发@Value、@Autowired等注解的注入逻辑,非托管类的注解不会被Spring处理,因此注入值始终为null。
修复步骤
- 给
MailServiceAuthProvider添加@Component注解(或对应业务场景的@Service、@Repository等衍生注解),如果没有自定义扫描其他包的需求,@ComponentScan可以直接删除:
@Component public class MailServiceAuthProvider { @Value("${my.name}") private String name; public void myMethod() { System.out.println(name); } }
- 检查启动类配置:
- 你原有的启动类定义
public class App()多了一对冗余括号,Java类定义不需要添加括号,直接修改为public class App - 如果
MailServiceAuthProvider不在启动类所在包及子包范围内,需要在@SpringBootApplication注解中补充扫描路径:
@SpringBootApplication(scanBasePackages = {"启动类所在包路径", "myservice"}) public class App implements CommandLineRunner { @Autowired MailServiceAuthProvider a; public static void main(String[] args) throws IOException { SpringApplication.run(App.class, args); } @Override public void run(String... args) throws Exception { a.myMethod(); } }
- 确认
application.properties放在src/main/resources根目录下,确保Spring可以正常读取配置。
修改完成后重新启动项目即可正常注入@Value对应的值。
内容的提问来源于stack exchange,提问作者obolen_an
相关产品推荐
相关产品推荐

