0

What's the minimal configuration needed to have the following class member to be initialized using the @Autowired annotations:

public class A {
  @Autowired
  private B b;
  // ...
}

When invoking A a = new A(), I'd like b to be initialized from a predefined bean without the need to configure it in code.

Probably some files are needed: A.java, web.xml, spring-context.xml (for configuring B) and jars(spring and a jar containing B).

What's the minimal needed configuration and files content?

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
  • Is Spring Boot an option? And just a heads up, you can't `new A()` and expect an autowired field inside it. The bean need to be managed and created by Spring to allow IoC. – dambros Apr 14 '16 at 16:30
  • Spring Boot is not an option. Trying to integrate to a servlet based webapp... – AlikElzin-kilaka Apr 14 '16 at 16:35

2 Answers2

0

Based on this post, I created the this project. Steps to have B initiated:

  1. Download and extract the compressed folder.
  2. Run mvn clean install.
  3. Copy the war (spring-autowired-1.0-SNAPSHOT.war) from the target to a web server's webapps folder.
  4. Run the server. (for tomcat: ./catalina.sh run)
  5. Call the API and see B's hascode - curl -X GET http://localhost:8080/spring-autowired-1.0-SNAPSHOT/rest/a/a.
  6. See b is initialized - not null.

The actual class:

@Component
@Path("/a")
public class A {

    @Autowired
    B b;

    @GET
    @Path("/a")
    public String a() {
        return b.toString();
    }
}

* The difference between my implementation vs. mkyong's is that my pom has less dependencies and @Autowired member is not an interface.

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
-2

If for some reason you cant configure class A to be a bean in your application context you can have class A implement SpringBeanAutowingSupport. This works in a web environment.

The SpringBeanAutowingSupport default constructor looks up the application context from the request. It then injects the dependencies.

public class A extends SpringBeanAutowiringSupport{
  @Autowired
  private B b;
}
ekem chitsiga
  • 5,523
  • 2
  • 17
  • 18
  • I'd like to not mix initialization technology with business logic. Inheriting from `SpringBeanAutowiringSupport` is something I'd like to evade doing. – AlikElzin-kilaka Apr 14 '16 at 16:47
  • Consider also the case where A might also inherit another business logic class. – AlikElzin-kilaka Apr 14 '16 at 16:47
  • Also, the question is about the spring+webapp configuration itself. Just inheriting a class won't really help here. Thanks for the effort. – AlikElzin-kilaka Apr 14 '16 at 16:48
  • Its a work around because you want to instantiate A yourself. This is against the Dependency Injection support in Spring. The simplest solution is to have Spring manage the bean. Just add it to the application context as other beans – ekem chitsiga Apr 14 '16 at 16:54