1

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

sp00m
  • 47,968
  • 31
  • 142
  • 252
Pith
  • 3,706
  • 3
  • 31
  • 44

3 Answers3

3

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.

Edvin Syse
  • 7,267
  • 18
  • 24
  • I don't want to use additionnal library and it seems that Tomcat 7 support Java EE 6. I don't think it is a problem with tomcat because i added the dependencies and JSF works fine ... – Pith Jun 07 '12 at 14:38
  • 2
    Tomcat doesn't support Java EE 6, that's why we built TomEE, to fill in the missing parts. DI is one of them. Check out this related stackoverflow question http://stackoverflow.com/a/9199893/190816 – David Blevins Jun 07 '12 at 15:51
2

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.

Sai Ye Yan Naing Aye
  • 6,622
  • 12
  • 47
  • 65
-1

Annotate MyServiceImpl with @Named annotation.

d1e
  • 6,372
  • 2
  • 28
  • 41