Bean 수동 등록, @Primary, @Qualifier

앞고기랑 소금·2024년 8월 23일

스파르타 TIL

목록 보기
27/43

27일차

Bean 수동 등록

  • Bean으로 등록하고자 하는 객체를 반환하는 메서드 선언후 @Bean 추가
  • Bean을 등록하는 메서드가 속해있는 해당 class위에 @Configuration 추가
@Configuration
public class PasswordConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Spring server가 뜰때 Spring IoC Container에 @Bean 메서드가 Bean으로 저장

  • 사용할땐 @Autowired 로 주입 받아서 사용
@Autowired
PasswordEncoder passwordEncoder;

같은 타입 Bean이 두개인경우

public interface Food {
    void eat();
}

@Component
// @Primary
public class Chicken implements Food {
    @Override
    public void eat() {
        System.out.println("치킨을 먹습니다.");
    }
}

@Component
// @Qualifier("pizza")
public class Pizza implements Food {
    @Override
    public void eat() {
        System.out.println("피자를 먹습니다.");
    }
}
  • bean이 두개라서 Autowired 할수없음.
@Autowired
Food food;

  • 방법 1 : bean이름으로 생성
@Autowired
Food chicken;
@Autowired
Food pizza;
  • 방법 2 : @Primary 사용
@Component
@Primary
public class Chicken implements Food {
    @Override
    public void eat() {
        System.out.println("치킨을 먹습니다.");
    }
}

public class BeanTest {
@Autowired
Food food;
}

디폴트 Bean으로 사용하고싶은 class에 @Primary쓰기

  • 방법 3 : @Qualifier 사용하기
@Component
@Qualifier("pizza")
public class Pizza implements Food {
    @Override
    public void eat() {
        System.out.println("피자를 먹습니다.");
    }
}

public class BeanTest {
@Autowired
@Qualifier("pizza")
Food food;
}
  • @Primary 보다 @Qualifier가 더 우선순위다
  • @Qualifier("pizza") ("")로 지정한 값은 사용하려할때 반드시 지정한 값과 같은 값을 넣어야함.

0개의 댓글