Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I inject a Java object using Spring without any xml configuration files?

Tags:

java

spring

I want to inject a plain java object using Spring programmatically without using any xml configuration. Want to inject fields/methods annotated with tags Like @EJB, @PostConstruct etc. Is that possible? Thanks!

like image 283
codeplay Avatar asked Sep 12 '10 06:09

codeplay


2 Answers

Creating an ApplicationContext without XML (using AnnotationConfigApplicationContext)

With AnnotationConfigApplicationContext, you don't need any XML at all. You create the Application context programatically and either

a) manually register annotated classes

appContext.register( MyTypeA.class,
                     MyTypeB.class,
                     MyTypeC.class );

b) or scan the classpath for annotated classes

appContext.scan(
    "com.mycompany.myproject.mypackagea",
    "com.mycompany.myproject.mypackageb"
)

If you use one of the convenience constructors

AnnotationConfigApplicationContext(Class<?> ... annotatedClasses)

or

AnnotationConfigApplicationContext(String ... basePackages)

the context is created and refreshed automatically, otherwise you need to call the refresh() method manually after adding the classes or packages.

Autowiring existing non-Spring beans (using AutowireCapableBeanFactory)

For autowiring an existing bean I think the preferred idiom is to use

appContext.getAutowireCapableBeanFactory().autowireBean(existingBean)

Or, if you want more control, use

appContext.getAutowireCapableBeanFactory()
      .autowireBeanProperties(
          existingBean,
          autowireMode,
          // e.g. AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE 
          dependencyCheck
      ) 

For further reference, see

like image 113
Sean Patrick Floyd Avatar answered Oct 06 '22 00:10

Sean Patrick Floyd


Yes, you can annotate any POJO with @Component, @Service, @Controller, or @Respository (depending on its responsibilities), and it becomes a spring bean. You just have to put this line into the applicationContext.xml:

<context:component-scan base-package="org.yourbasepackage" />

You can also use @PostConstruct and @PreDestroy instead of the xml init-method and destroy-method.

Update: There is a project called spring-javaconfig. Parts of it have become part of the core spring and you can see more details here. In short, it allows you to use java classes instead of xml for configuring your beans.

like image 43
Bozho Avatar answered Oct 06 '22 01:10

Bozho