package com.spring4.practice01;
public interface Car {
public String brand();
}
package com.spring4.practice01;
public class CarImpl implements Car {
@Override
public String brand() {
return "자동차는 삼성 SM5입니다";
}
}
package com.spring4.practice01;
public interface Tire {
public String mount();
}
package com.spring4.practice01;
public class TireImpl implements Tire {
public String mount(){
return "타이어는 한국타이어 장착했네요.";
}
}
package com.spring4.practice01;
import org.springframework.beans.factory.annotation.Autowired;
public class Service {
@Autowired
Car car;
@Autowired
Tire tire;
public Service(){
}
public void test(){
System.out.println("테스트입니다.");
System.out.println("Car객체: "+car);
}
public void print(){
System.out.println("car: "+car.brand());
System.out.println("tire: "+tire.mount());
}
}
package com.spring4.practice01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class CarMain {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
Service service = (Service)ctx.getBean("service",Service.class);
service.print();
service.test();
}
}
자바 설정 파일:
자바설정 파일 테스트를 위해 pom.xml 파일에 cglib를 추가해야한다.
pom.xml 파일에 추가해서 메이븐으로 자동 다운로드 받으면 된다.
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.3</version>
</dependency>
package com.spring4.practice01;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.spring4.practice01.CarImpl;
import com.spring4.practice01.Tire;
import com.spring4.practice01.Service;
@Configuration
public class JavaConfig {
@Bean
public Car car(){
return new CarImpl();
}
@Bean
public Tire tire(){
return new TireImpl();
}
@Bean
public Service service(){
return new Service();
}
}
생성자 방식은 요약해서 아래에 기술한다.
@Bean
public Service service(){
return new Service(car(), tire());
}
public Service(){
}
public Service(Car car, Tire tire){
this.car = car;
this.tire = tire;
}
// 위에 처럼 생성자에다가 직접 값을 넣고, 받으면 됨.
public void test(){
System.out.println("테스트입니다.");
System.out.println("Car객체: "+car);
}
'기존카테고리 > Spring_문법' 카테고리의 다른 글
servletSession과 springSession (0) | 2017.07.27 |
---|---|
스프링 DI(Dependency Injection) 2 (0) | 2017.07.23 |
스프링 DI(Dependency Injection) 1 (0) | 2017.07.23 |
Parameter값 받기 - 실전(Command객체) (0) | 2017.07.13 |
Parameter값 받기 - 기초(@RequestParam) (0) | 2017.07.13 |