简体   繁体   中英

How to inject an external-defined class in Java EE

Supposing I would like to use a Foo class defined by an external library written in JavaSE (and assuming that I cannot edit it).

In Spring , I can declare this class as bean by writing:

@Bean
public Foo foo() {
    return new Foo();
}

Then, it is possible to perform the DI:

@Autowired
private Foo foo;

Is there a way to do the same in Java EE (if possible, by avoiding the inheritance)?

In CDI, you dont even have to annotate the pojo.

Consider that the following has been declared in an external library:

public class MyService{}

And then in your project, you can have a stateless ejb or just another CDI bean.

@Stateless
public class MyController{

 @Produces
 public MyService getMyService(){
  return new MyService();
 }
}

Now from somewher else in your controller

@SessionScoped
@Named
public class MySessionController implements Serializable{
  //simple, just inject and the producer method will be called automatically
  @Inject
  private MyService service;
}

You need to check on Producers and Stereotypes from the url:

Producers and Stereotypes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM