2012-03-02 2 views
2

스프링 어플리케이션을 시작하기위한 주석 기반 메소드가 있는지 궁금합니다.스프링 응용 프로그램 컨텍스트를 가져 오는 주석 기반 방법이 있습니까?

즉 교환이 아래 일 : 통계 기반 방법으로

public static void main(String[] args) { 

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

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

} 

을 빈에 다음을 Autowiring은 컨텍스트를 얻고 위해?

답변

0

ClassPathApplicationContextXml 코드를 피할 수는 없지만 아래와 같이하면 ctx.getBean ("user")을 피할 수 있습니다. 이상적인 것은 XML이 사물을 주입하고 싶은 곳의 패키지를 스캔하도록 xml에 요청하는 것이다. Spring 클래스는 스프링 클래스로 선언되므로 스프링 클래스로 내 메인 클래스를 만들고 있기 때문에 여기서는 안됩니다. Classpathapplicationcontext를 사용하여 xml을로드하는 것을 피할 수 없습니다. 테스트를 위해 @ContextConfiguration 매우 helpfull 전화 : 봄의 말뭉치 주석이 있습니다

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(); 
    } 

} 
3

나는 모든 사람이 그 주석을 이해하고 처리해야만한다고 생각합니다. Spring이 아직 초기화되지 않았다면 누가 할 것인가?

1

. 테스트 지원 (testNG or JUnit)을 위해 생성 된 봄 추상 클래스 중 하나를 확장해야합니다.

(예 AbstractTransactionalTestNGSpringContextTests 토르 testNG 또는 JUnit을위한 AbstractTransactionalJUnit4SpringContextTests) 다음

그냥 @ContextConfiguration 주석을 사용 (클래스,() 주석 형을 포함하여 인터페이스 또는 열거 선언) junit에 대한

몇 가지 예제 코드 테스트 :

@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... 
} 

은 읽어 보시기 바랍니다 : http://static.springsource.org/spring/docs/2.5.x/reference/testing.html

관련 문제