我正在研究 java 中的依赖注入示例,大多数文档都强调我必须在其中放置一个beans.xml
空
- META-INF 如果是 jar 应用程序
- WEB-INF 如果是 Web 应用程序
所以,我使用战争类型的包装,但是,我的应用程序只有在我放入beans.xml
META-INF 文件夹时才有效。我对为什么它以这种方式工作有点困惑?我将我的战争文件部署在 JBOSS/WildFly 容器中。
这是我的简单pom.xml
beans.xml 位于src/main/resources/META-INF
同样在这里你可以看到我只使用了哪些注解来注入 bean。
自动服务.java
public interface AutoService {
void getService();
}
BMWAutoService.java
@Named("bmwAutoService")
public class BMWAutoService implements AutoService{
@Override
public void getService() {
System.out.println("You chose BMW auto service");
}
}
AutoServiceCaller.java
@Named
public class AutoServiceCallerImp implements AutoServiceCaller{
private AutoService bmwAutoService;
@Inject
public AutoServiceCallerImp(@Named("bmwAutoService") AutoService bmwAutoService) {
this.bmwAutoService = bmwAutoService;
}
@Override
public void callAutoService() {
// get bmw's auto service
bmwAutoService.getService();
}
}