@Component, @Bean 사용자 Bean 등록하는 두가지 방법 > 스프링 부트

본문 바로가기

[개발] @Component, @Bean 사용자 Bean 등록하는 두가지 방법

필기자
2022-09-06 14:23 2,844 0

본문

빈(Bean)은 스프링 컨테이너가 생성한 객체라고 인식하면 된다.

JAVA에서는 일반적으로 Class를 객체화 할때 아래와 같이 new 키워드를 통해 객체를 생성한다.



Weapon swp = new Weapon(); 

 

Bean은 스프링 컨테이너가 미리 생성한 객체 이므로 가져다 쓰기만 하면 된다.

객체 주입이라고 하며 @Autowired 어노테이션을 사용한다.



@Autowired
private Weapon swp;

 



private final Weapon bwp;

@Autowired
public UserBeanController(Weapon bwp) {
    this.bwp = bwp;
}

 

스프링 부트는 어노테이션을 통한 빈 등록을 기본으로 함 
필요한 Bean을 등록하고, 필요한 위치에서 @Autowired를 통해 주입받아 사용함
@Service, @Controller, @Repository, @Component, @Configuration, @Bean  등

 

20220906135837_ddfa29dc4cb6a70c618839d7aa582e62_iq1v.png

 

프로젝트 구조

 

20220907121104_ddfa29dc4cb6a70c618839d7aa582e62_39hn.png

 

빈 등록방법 1-1: shop/component/Weapon.java 인터페이스 생성



public interface Weapon {
    void fire();
    String getModel();
}

 

빈 등록방법 1-2: component/ShotGun.java Weapon을 상속 받는 구현체 생성(@Component 방법으로 등록)



@Component // 사용자 정의 빈 등록
@Qualifier("basicShotGun") // Bean의 구체적인 선별 방법
@Primary // 같은 Bean 객체 주입시 우선 순위 지정
public class ShotGun implements Weapon {
    private String model = "Basic ShotGun";

    @Override
    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    @Override
    public void fire() {
        System.out.println(model+" fire!!");
    }
}

 

빈 등록방법 1-3: component/BasicConfiguration.java 파일 생성(@Configuration > @Bean 방법으로 등록)



@Configuration // @Bean 메소드 사용을 위해 선언
public class BasicConfiguration {
    @Bean // 사용자 정의 Bean 등록
    @Qualifier("superShotGun") // @Bean(name="superShotGun") 대체 가능
    public Weapon superShotGun(){
        ShotGun sg = new ShotGun();
        sg.setModel("Super ShotGun");
        return sg; // @Bean 메소드는 반드시 객체를 반납
    }
}

 

빈 등록방법 1-4: controller/UserBeanController.java 컨트롤러 생성



@Controller
public class UserBeanController {
    @Autowired // 필드 주입 방법
    @Qualifier("superShotGun")
    private Weapon swp;

    private final Weapon bwp; // 생성자 주입시 final 선언

    @Autowired // 생성자 주입 방법
    public UserBeanController(Weapon bwp) {
        // @Qualifier("basicShotGun")가 Weapon 타입의 객체의 @Primary 선언으로 생략 가능
        this.bwp = bwp;
    }
    /*
    @Autowired // 생성자 주입 방법
    public UserBeanController(@Qualifier("basicShotGun") Weapon bwp) {
        this.bwp = bwp;
    }
    */

    @GetMapping("/b")
    public String main(Model m){
        m.addAttribute("name","홍길동");
        m.addAttribute("weapon", bwp.getModel());
        return "user_bean";
    }

    @GetMapping("/s")
    public @ResponseBody ResponseEntity<Model> get(Model m) {
        m.addAttribute("name","홍길동");
        m.addAttribute("weapon", swp.getModel());
        return new ResponseEntity<Model>(m, HttpStatus.OK);
    }
}

 

빈 등록방법 1-5: templates/user_bean.html View 생성



<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>사용자 정의 빈 확인</title>
</head>
<body>
<h1 th:with="say=${name} + '님 방갑습니다. ' + ${name} +'님 무기는 '+ ${weapon} + '입니다.'" th:text="${say}">방가워요.</h1>
</body>
</html>

 

[결과 확인]

 

http://localhost:8080/b

 

20221101135754_58c21c62e2e6f71b42558e4bc6ecc1e2_801x.png

 

http://localhost:8080/s

 

20221101135812_58c21c62e2e6f71b42558e4bc6ecc1e2_f9fc.png

댓글목록0

등록된 댓글이 없습니다.
게시판 전체검색