Pith
Pith

Reputation: 3794

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

Upvotes: 1

Views: 2303

Answers (3)

Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6738

You only need to add beans.xml file in the (META-INF/beans.xml or WEB-INF/beans.xml). This is sample beans.xml file,

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
            http://java.sun.com/xml/ns/javaee 
            http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
      </beans>

Read this article, its explained detail usage of DI.

Upvotes: 2

Edvin Syse
Edvin Syse

Reputation: 7297

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.

Upvotes: 3

d1e
d1e

Reputation: 6452

Annotate MyServiceImpl with @Named annotation.

Upvotes: -1

Related Questions