要让@Autowired注解起作用,确保以下几点:
在应用程序的配置文件中启用自动注入(即使用@EnableAutoConfiguration或@Configuration注解)。
在要注入的类上使用@Autowired注解。
确保要注入的类在Bean的应用程序上下文中。
下面是一个示例代码,演示如何使用@Autowired注解在应用程序上下文中注入Bean:
// 在配置类中启用自动配置
@Configuration
@EnableAutoConfiguration
public class AppConfig {
// 创建一个Bean
@Bean
public MyBean myBean() {
return new MyBean();
}
}
// 要注入的类
@Component
public class MyComponent {
// 使用@Autowired注解注入Bean
@Autowired
private MyBean myBean;
// ...
}
// 测试类
public class Main {
public static void main(String[] args) {
// 创建应用程序上下文
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// 从应用程序上下文中获取MyComponent Bean
MyComponent myComponent = context.getBean(MyComponent.class);
// 使用注入的Bean
myComponent.myBean.doSomething();
}
}
在上面的示例中,MyComponent类使用@Autowired注解注入了MyBean类。在Main类中创建应用程序上下文后,可以从上下文中获取MyComponent Bean,并使用注入的MyBean实例调用doSomething()方法。
下一篇:Bean找不到所需的依赖项。