Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[20220811] FactoryBean 인터페이스를 사용하여 Spring Bean 등록 #263

Open
JuHyun419 opened this issue Aug 10, 2022 · 0 comments
Open
Labels

Comments

@JuHyun419
Copy link
Owner

JuHyun419 commented Aug 10, 2022

FactoryBean 인터페이스를 사용하여 Spring Bean 등록

  • FactoryBean 인터페이스 코드
public interface FactoryBean<T> {
    String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";

    @Nullable
    T getObject() throws Exception;

    @Nullable
    Class<?> getObjectType();

    default boolean isSingleton() {
        return true;
    }
  • 생성자가 private일 때, FactoryBean 사용하여 빈으로 등록하기
public class Message {
    private String text;

    private Message(String text) {
        this.text = text;
    }

    public static Message newMessage(String text) {
        return new Message(text);
    }

    public String getText() {
        return text;
    }
}


import org.springframework.beans.factory.FactoryBean;

public class MessageFactoryBean implements FactoryBean<Message> {

    private String text;

    public MessageFactoryBean(String text) {
        this.text = text;
    }

    // 실제 빈으로 사용될 오브젝트 생성 -> Message
    @Override
    public Message getObject() throws Exception {
        return Message.newMessage(this.text);

        // FactoryBean을 사용하여 스프링 빈으로 등록할 수 없는 동적 프록시 오브젝트를 빈으로 생성
        //return Proxy.newProxyInstance(...)
    }

    @Override
    public Class<?> getObjectType() {
        return Message.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}


// Test
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@ContextConfiguration
class MessageFactoryBeanTest {

    @Autowired
    private ApplicationContext context;

    @Test
    void getMessageFactoryBean() {
        Object message = context.getBean("message");

        assertAll(
                () -> assertThat(message).isInstanceOf(Message.class),
                () -> assertThat(((Message) message).getText()).isEqualTo("Factory Bean")
        );
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant