非Spring Boot应用中如何使用@Configuration与@Bean注解?
在非Spring Boot应用中使用@Configuration和@Bean的方法
一、先引入必要的Spring依赖
如果是Maven项目,在pom.xml中添加Spring核心容器依赖:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.20</version> <!-- 选择合适的稳定版本 --> </dependency>
二、编写@Configuration和@Bean配置类
你提供的CoreBeansConfig写法是正确的,补充几个关键点:
@Configuration标记该类为Spring的配置类,容器会解析其中的@Bean方法@Bean方法的参数会自动从容器中获取对应实例(比如YelpRestGateway也需要是容器中的Bean)
如果YelpRestGateway尚未注册,可在同一配置类中添加Bean定义:
@Configuration public class CoreBeansConfig { @Bean public YelpRestGateway yelpRestGateway() { return new YelpRestGateway(); // 根据实际构造逻辑创建实例 } @Bean public YelpService yelpServiceImpl(YelpRestGateway yelpRestGateway){ return new YelpServiceImpl(yelpRestGateway); } }
三、手动初始化Spring容器
非Spring Boot应用不会自动启动容器,必须手动初始化并加载配置类:
public class MainApp { public static void main(String[] args) { // 通过AnnotationConfigApplicationContext加载配置类,创建Spring容器 ApplicationContext context = new AnnotationConfigApplicationContext(CoreBeansConfig.class); // 从容器中获取Bean,此时依赖已自动注入 YelpService yelpService = context.getBean(YelpService.class); // 调用业务方法 yelpService.processRequest(); } }
四、让@Inject注解生效
如果其他类需要用@Inject注入Bean,该类必须被Spring容器管理:
比如有一个业务类BusinessHandler:
import javax.inject.Inject; // 用@Component标记,让Spring扫描并注册为Bean @Component public class BusinessHandler { private final YelpService yelpService; // 推荐用构造注入,避免字段注入的弊端 @Inject public BusinessHandler(YelpService yelpService) { this.yelpService = yelpService; } public void handleBusinessTask() { yelpService.processRequest(); } }
要让Spring扫描到@Component,需在配置类上添加@ComponentScan指定包路径:
@Configuration @ComponentScan(basePackages = "com.your.project.package") // 替换为你的实际包路径 public class CoreBeansConfig { // 你的@Bean方法... }
或者直接用@Bean注册该类:
@Bean public BusinessHandler businessHandler(YelpService yelpService) { return new BusinessHandler(yelpService); }
关于你之前的问题
你用@Inject后类无法被识别,核心原因是没有启动Spring容器——你自己new的类不在Spring管理范围内,容器不会处理@Inject注解。只有当类通过@Component、@Bean等方式注册到容器,且容器完成初始化后,依赖注入才会生效。
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

