您需要使用@Bean 注解将 bean 提供给 WebApplicationContext。我已经从 @Configuration bean 中的 context.xml 创建了 managerService bean,并使用 @Bean 方法使 bean 在 webApplicationContext 中可用。这个将 managerService 自动连接的 UserService 类具有此配置 bean 的属性 @ConditionalOnBean。
以下是我的实现方式。
应用类
@SpringBootApplication public class DemoApplication
{
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}
用户服务
@Service
@ConditionalOnBean({EnableConfiguration.class})
public class UserService
{
@Autowired
private ManagerService managerService;
public String run() {
System.out.println("Going to Run from manager Service");
return managerService.run();
}
}
启用配置
@Configuration
public class EnableConfiguration implements InitializingBean
{
ManagerService managerService;
@Bean
public ManagerService mngrService() {
return managerService;
}
@Override public void afterPropertiesSet() throws Exception
{
ApplicationContext ctx = new ClassPathXmlApplicationContext( "context.xml" );
managerService = (ManagerService) ctx.getBean("managerService");
System.out.println("manager bean:" + managerService.toString());
mngrService();
}
}
ManagerService
public class ManagerService
{
private int a;
private int b;
public ManagerService(int a, int b) {
this.a = a;
this.b = b;
}
public String run() {
return this.toString();
}
@Override public String toString()
{
return "ManagerService{" + "a=" + a + ", b=" + b + '}';
}
}
服务控制器
@RestController
public class ServiceController
{
@Autowired
private UserService userService;
@GetMapping("/get")
public String test() {
return userService.run();
}
}
context.xml
<bean id="managerService" class="com.example.demo.ManagerService">
<constructor-arg index="0" value="2"/>
<constructor-arg index="1" value="5"/>
</bean>