2014-10-06 5 views
0

스프링 프레임 워크에서 작업을 시작하고 있습니다. 콩 개념을 머리에 쓰려고합니다. 빈 값이있는 경우스프링 빈 값 주입

public class CurrentDateServiceImpl implements CurrentDateService { 
    public LocalDate getCurrentDate() { 
     return LocalDate.now() ; 

    } 

내가 달성하기 위해 노력하고있어 주장하는 간단한 @Test가 : 현재 날짜를 얻을

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 

    <bean id= "currentDateService" class ="xx.CurrentDateSerivceimpl" /> 
</beans> 

그리고 클래스 : 나는 xml 파일이 현재 공급되는 날짜와 동일합니다. 나는 시험에 빈의 값을 제공 할 수있는 방법을 모르고있어

@Test 
public void test() { 
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml"); 
    CurrentDateServiceImpl currentDateServiceObj = (CurrentDateServiceImpl) context.getBean("currentDateService"); 
    LocalDate date = LocalDate.now(); 
    LocalDate date2 = "the value of the bean"; 
    assertEquals(date, date2); 
} 

, 나는 그것을 수행하는 방법을 궁금하고이 있다면 :

내가에 붙어 것은 스프링 문서 자체를 제외하고 어떤 좋은 자습서/문서화

편집 :

package lt.insoft.app.bl.service.impl; 

import static org.junit.Assert.assertEquals; 

import java.time.LocalDate; 

import lt.insoft.app.bl.service.CurrentDateService; 
import lt.insoft.app.bl.service.CurrentDateServiceFormat; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "file:src/main/resources/META-INF/application-context.xml" }) 
public class CurrentDateServiceImplTest { 

@Autowired 
CurrentDateService service; 
CurrentDateServiceFormat service2; 


    @Test 
    public void test() { 

     LocalDate date = LocalDate.now(); 
     LocalDate date2 = service.getCurrentDate();  
     String date3 = service2.formatCurrentDate(); 
     System.out.println(date3); 
     assertEquals(date, date2); 
    } 

} 

왜이 포맷 된 날짜를 인쇄되지 않는 이유는 무엇입니까?

+1

단순히 전화'currentDateServiceObj.getCurrentDate을()' – Jens

+0

손으로 모든 작업을 수행 할 필요가 없습니다. 새로운 코드의 경우 일반적으로 XML을 통한 JavaConfig를 권장하고 빈 조회에 대한 주입을 권장합니다. – chrylis

답변

1

테스트를 위해 스프링 지원을 사용하십시오. 코드는보다 명확하고 이해하기 쉽습니다.

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"application-context.xml"}) 
public class TestClass{ 

@Autowired 
CurrentDateService service; 

@Test 
public void test() { 

    LocalDate date = LocalDate.now(); 
    LocalDate date2 = service.getCurrentDate(); 
    assertEquals(date, date2); 
} 
} 

난 당신이 뭔가하고 싶었던 생각 :

public class CurrentDateServiceImpl implements CurrentDateService { 
    public LocalDate getCurrentDate() { 
     return LocalDate.now() ; 

    } 
} 

public class CurrentDateServiceFormatImpl implements CurrentDateServiceFormat{ 
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); 

    CurrentDateService service; 

    public void myMethod(){ 
     return service.getCurrentDate().format(FORMATTER); 
    } 

    public void setService(CurrentDateService service){ 
     this.service = service; 
    } 
} 

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 

    <bean id= "currentDateService" class ="xx.CurrentDateSerivceimpl" /> 
    <bean id= "CurrentDateServiceFormat" class ="xx.CurrentDateServiceFormatImpl"> 
    <property name="service" id-ref="currentDateService"/> 
    </bean> 
</beans> 
+0

고맙습니다, 후속 질문이 있지만 콩이 실제로 무엇인지 이해하지 못하는 것 같습니다. 여기에 질문을 더 게시해야합니까? – Monty

+0

좋아, 나는 exmplain하려고합니다. 일반적인 자바 애플리케이션 (콘솔)에서는 많은 클래스 인스턴스를 생성하고 전달해야한다. 봄에는 그렇게 할 필요가 없습니다. 스프링을 (자바 정의에서) 어떻게 java 클래스를 생성하는지 (예 : 어떤 인자가 있는지) 알려주고, 빈을 생성 할 때 클래스의 인스턴스를주기 위해 Spring에 요청할 수있다. 따라서 자바 인스턴스 (Beans)로 만든 컨테이너를 만들고 클래스 (다른 Bean) 필요를 채우기 위해 사용할 수 있습니다. 이 주제에 대한 자세한 내용은 "의존성 주입"을 구글로 볼 수 있습니다. – Beri

+0

내가 이해하려고하는 것은 콩 사이에 값을 전송하는 방법입니다. 예를 들어 로컬 날짜를 가져 와서 형식을 변경하려고합니다. public String CurrentDateServiceFormat() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern "dd-MM-yyyy"); String formattedDateTime = dateTime.format (formatter); return formattedDateTime; } dateTime은 getCurrentDate 메소드로 얻은 현재 날짜를 이해하는 이전 bean의 값과 같아야합니다. 하지만 어떻게 다음 방법으로 제공 할 수 있습니까? – Monty