Search code examples
javadependency-injectionjava-ee-6java-6

DI with Java 6?


I read some documentation on DI with Java 6 and I'm not sure to fully understand. I have the following class in which I want to inject a service:

@ManagedBean
@RequestScoped
public class MyBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private MyService myService;
    private List<SomeObject> someObjects;

    // Getter and setter

    public List<SomeObject> getSomeObjects() {
        if (someObjects == null) {
            someObjects = myService.find();
        }
        return someObjects;
    }

}

The service:

public class MyServiceImpl implements MyService {

    public MyServiceImpl() {
    }

}

When running this code, myService is not injected. Please, what am I doing wrong?

PS: I'm using Tomcat 7


Solution

  • Java 6 does not have built in dependency injection, nor does Tomcat 7 AFAIK. Are you thinking about Java EE 6? Then you have to run your code in a Java EE 6 compatible appserver, like TomEE or GlassFish.

    If you want to stay with Tomcat 7, you could concider Spring or Guice instead.