본문 바로가기
Web과 프로그래밍 언어/JAVA

[Spring/스프링] Annotation 어노테이션 (@Autowired, @Qulifier, @Component, @Value)의 사용과 java configuration 의 사용

by cosmicgy 2023. 6. 30.

어노테이션

어노테이션을 이용해서 설정을 코드와 함께 가져가는 방법. 요즘에 많이 사용됨.

 

  • @Autowired
<property name="exam" ref="exam" />

을 xml 파일에 작성할 필요없이 java 코드에 아래와같이 작성.

@Autowired
private Exam exam;

 

required 속성의 사용 가능. settins 에 객체가 없어도 null 로 진행됨.

@Autowired(reuqired=false)
@Qualifier("exam2")
private Exam exam;

단, setting.xml파일에 context namespaces 체크한뒤 <context:annotation-config /> 추가해야함

 

  • @Qualifier

Autowired가 무엇을 기준으로 injection 해주는지 명시

<bean id="exam1" class="srping.di.entity.NewLecExam" p:kor="10" p:eng="10" />
<bean id="exam2" class="srping.di.entity.NewLecExam" p:kor="20" p:eng="20" />
@Autowired
@Qualifier("exam1")
@Override
public void setExam(Exam exam)
    this.exam = exam;

 

  • @Component

어노테이션을 이용한 객체 생성 방법. setting.xml 파일에서 <context:component-scan base-pakage="spring.di.ui"/> 입력해주어야 사용가능.
<context:annotation-config />는 삭제해도 됨. 그리고 @Component("console") 이렇게 객체 생성 시 이름을 부여할 수 있다.

두개의 패키지를 스캔하도록 할 때에는 <context:component-scan base-pakage="spring.di.ui, spring.di.entity" />처럼 콤마 찍어서 입력.

 

  • @Value

기본값 설정을 위한 어노테이션. 객체에 값을 설정하지 않아도 기본 값을 갖고 객체 생성.

@Component
public class NewlecExam implements Exam {
    @Value("10")
    private int kor;
    @Vlaue("20")
    private int eng;
    private int math;
    private int com;
}
// kor = 10, eng = 20
  • @Service, @Controller, @Repository 모두 @Component 와 동일하게 사용 가능하나, 객체화하는 클래스가 어떤 역할을 하는 클래스인지 명시 가능

 

XML Configuration을 Java Configuration으로 변경

 

설정을 위한 java class임을 명시하기 위해 @COnfiguration 을 사용

<context:conponent-scan base-package="spring.di.ui" />
<bean id="exam" class="spring.di.entity.NewlecExam" />

을 아래와 같이 자바 클래스로 변환

// NewlecAppConfig.java
@ComponentScan("spring.di.ui")
@Configuration
public class NewlecAppConfig{
    @Bean
    public Exam exam() { //여기서의 exam은 함수명이 아닌 contatiner에 담겨질 때의 이름으로 보는 것이 맞다. xml파일에서의 bean id
        return new NewlecExam();
    }

}
// Program.java
// ApplicationContext context = new ClassPathXmlApplicationContext("spring/di/setting.xml")
ApplicationContext context = new AnnotationConfigApplicationContext(NewlecAppConfig.class);

 

  • register 함수
    여러개의 config.class를 설정하거나 분리해서 설정할 수 있음
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(NewlecAppConfig.class);
// ctx.register(AppConfig.class, OtherConfig.class) 이렇게 쉼표로 구분해서 여러개 사용 가능
ctx.refresh();

'Web과 프로그래밍 언어 > JAVA' 카테고리의 다른 글

[Spring/스프링] IOC 컨테이너와 DL, DI  (0) 2023.06.30