john
john

Reputation: 23

Is there an annotations based method for getting springs application context?

I was wondering is there an annotations based method for starting a spring application?

i.e. replacing this below:

    public static void main(String[] args) {

    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");  

    User user = (User)ctx.getBean("user");
    user.createUser();

}

With an annotations based method for getting the context and then Autowiring in the bean?

Upvotes: 2

Views: 2125

Answers (3)

Andy602
Andy602

Reputation: 51

There is an anotation in spring: called @ContextConfiguration Very helpfull for testing. You need to extend one of the spring abstract classes created for test support(testNG or JUnit).

(e.g. AbstractTransactionalTestNGSpringContextTests tor testNG or AbstractTransactionalJUnit4SpringContextTests for JUnit)

Then you just use the @ContextConfiguration annotation(for Class, interface (including annotation type), or enum declaration)

some example code for junit test:

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
// in the root of the classpath
@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})
public class MyTest {
    // class body...
}

please read: http://static.springsource.org/spring/docs/2.5.x/reference/testing.html

Upvotes: 1

raddykrish
raddykrish

Reputation: 1866

You cannot avoid that ClassPathApplicationContextXml code but you can avoid that ctx.getBean("user") by doing as below. Ideally what it does is it asks the xml to scan the packages where spring want to inject things. The only thing you should not here is that i have declared my main class as spring Component, since springs annotations work on spring recognized classes and hence i am making my main as spring recognized class. The loading of xml using Classpathapplicationcontext cannot be avoided.

package com.spring.sample;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.spring.sample.component.Sample;

@Component
public class SampleMain {

    @Autowired
    Sample testSample;

    static ApplicationContext appCtx = new ClassPathXmlApplicationContext("META-INF/webmvc-application.xml");

    public static void main(String[] args){

        SampleMain sampleMain = appCtx.getBean(SampleMain.class);
        sampleMain.invokeSample();
    }

    private void invokeSample(){
        testSample.invokeSample();
    }

}

Upvotes: 0

gpeche
gpeche

Reputation: 22514

I don't think you can do that, after all someone would have to understand and process that annotation. If Spring has not initialized yet, who would?

Upvotes: 3

Related Questions