简体   繁体   中英

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

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!

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

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.

The documentation around annotation-based Spring configuration can be found here . You will need a minimal amount of XML, so that Spring knows to look for annotation-based configuration:

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

Once that is done, you can use the @Autowired annotation to set up your beans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM