본문 바로가기

Web/spring

[Spring framework Core] 1.3. Bean Overview

728x90

틀린 해석이 있다면 알려주세요


 

1.3. Bean Overview

< 번역하면 콩이라 좀 웃김 >

 

 

 

Spring IoC Container 는 하나 이상의 빈을 관리한다.

이 빈은 컨테이너를 구성하는 구성 메타데이터 (XML 형식의 <bean/>) 으로 생성된다.

 

컨테이너 자체 내에서 이 BeanDefinition 객체로 표시된다

  • A package-qualified class name: typically, the actual implementation class of the bean being defined.
  • Bean behavioral configuration elements, which state how the bean should behave in the container (scope, lifecycle callbacks, and so forth).
  • References to other beans that are needed for the bean to do its work. These references are also called collaborators or dependencies.
  • Other configuration settings to set in the newly created object — for example, the size limit of the pool or the number of connections to use in a bean that manages a connection pool.

패키지 수식 클래스명 -> 식제 구현 클래스

빈의 동작 구성 요소 -> 범위, 라이프사이클, 콜백 등

빈이 일을 할때 필요한 다른 빈의 참조 정보 -> collaborators 또는 dependencies

새로 생성된 객체에 대한 기타 구성 

 

 

 

 

Table 1. The bean definitionPropertyExplained in…​

Class Instantiating Beans
Name Naming Beans
Scope Bean Scopes
Constructor arguments Dependency Injection
Properties Dependency Injection
Autowiring mode Autowiring Collaborators
Lazy initialization mode Lazy-initialized Beans
Initialization method Initialization Callbacks
Destruction method Destruction Callbacks

 

ApplicationContext 는 컨테이너 외부에서 생성된 기존 객체의 등록도 허용된다고 한다.

내가 앱을 공부할때 context 를 위임, 대리한다 라는 식으로 해석하면서 사용했었는데 

스프링에서도 이 메소드의 BeanFactory - getBeanFactory() 메소드를 통해 객체 등록등에 대한 수행을 지원하는 듯 하다

DefaultListableBeanFactory 는 registerSingleton(), registerBeanDefinition() 등으로 지원한다고 한다

 

Bean metadata and manually supplied singleton instances need to be registered as early as possible, in order for the container to properly reason about them during autowiring and other introspection steps. While overriding existing metadata and existing singleton instances is supported to some degree, the registration of new beans at runtime (concurrently with live access to the factory) is not officially supported and may lead to concurrent access exceptions, inconsistent state in the bean container, or both.

 

런타임 시에 새 빈 등록은 공식적으로 지원되지 않는다.

미리 등록해두라는 뜻

 

public final Service service; << initialize 시켜줘야함

public ServiceImpl(Service service){
	this.service = service;
}

(~)

이렇게 먼저 선언해주지 않으면 오류난다는 뜻인 듯 하다.

 

 

 

1.3.1. Naming Beans

콩 이름 짓기zzzzㅋㅋㅋ

 

모든 빈에는 식별자가 있어야하고, 이는 빈을 호스팅하는 컨테이너 내에서 고유해야한다

Bean 에는 일반적으로 식별자가 하나만 있고, 둘 이상이 필요하면 추가 항목을 별칭으로 간주할 수 있다

 

XML 기반 메타데이터에서 id, name 둘을 이용하여 식별자를 지정하고

속성을 사용하면 정확하게 하나의 id를 지정해줄 수 있다 (myBean, someService) 뿐 아니라 특수문자도 포함될 수 있다고 한다

bean 에 대한 다른 별명을 도입하려는 경우 3.1버전부터   comma (,), semicolon (;), or white space 로 구분해서 지정할 수도 있다고 한다

As of 3.1, it is defined as an xsd:string type. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.

 

빈에 이름일 제공하지 않더라도 명시적으로 컨테이너는 해당 빈에게 고유한 이름을 생성해주긴하지만

우리가 쓸려면 당연히 이름을 제공해줘야한다

 

명명규칙은 표준 Java 규약을 사용한다

소문자로 시작한 카멜케이스이다

 

Naming beans consistently makes your configuration easier to read and understand. Also, if you use Spring AOP, it helps a lot when applying advice to a set of beans related by name.

 

 

With component scanning in the classpath, Spring generates bean names for unnamed components, following the rules described earlier: essentially, taking the simple class name and turning its initial character to lower-case.

클래스 경로에서 구성 요소 검색을 하면 스프링은 이름이 지정되지 않은 구성요서에 빈 이름을 생성해준다

 

 

However, in the (unusual) special case when there is more than one character and both the first and second characters are upper case, the original casing gets preserved.

These are the same rules as defined by java.beans.Introspector.decapitalize (which Spring uses here).

 

 

Aliasing a Bean outside the Bean Definition

bean 을 정의할 때 지정된 id와 다른 조합을 이용해서 공통 종속성을 참조하도록 하여 별칭을 지정해줄 수 는 있다.

<alias name="fromName" alias="toName"/>

이 경우에는 name 뿐 아니라 alias의 이름으로도 참조될 수 있다.

 

the configuration metadata for subsystem A may refer to a DataSource by the name of subsystemA-dataSource. The configuration metadata for subsystem B may refer to a DataSource by the name of subsystemB-dataSource. When composing the main application that uses both these subsystems, the main application refers to the DataSource by the name of myApp-dataSource. To have all three names refer to the same object, you can add the following alias definitions to the configuration metadata:

 

<alias name="myApp-dataSource" alias="subsystemA-dataSource"/>
<alias name="myApp-dataSource" alias="subsystemB-dataSource"/>

이름은 같은데 별칭을 주어서 충돌하지않지만

동일한 빈을 참조할 수 있다.

 

Java 구성을 사용하는 경우 @Bean 애노테이션을 사용하여 별칭을 제공할 수 있다.

 

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-java-bean-annotation

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

 

 

Instantiation with a Constructor

생성자 접근 방식으로 빈을 생성하면 모든 일반 클래스가 스프링에서 사용 호환 된다.

개발 중인 클래스는 특정 인터페이스를 구현하거나 특정 방식으로 코딩하지않고

단순히 클래스를 지정하기만 하면 된다

but 특정 빈 IoC 유형에 따라 필요할 수는 있다

 

pring IoC 컨테이너는 관리하려는 거의 모든 클래스를 관리할 수 있다. 

<bean id="exampleBean" class="examples.ExampleBean"/>

<bean name="anotherExample" class="examples.ExampleBeanTwo"/>
 

생성자에 인수를 제공하고(필요한 경우) 개체가 생성된 후 개체 인스턴스 속성을 설정 방법 :  종속성 주입 

 

 

 

Instantiation with a Static Factory Method

정적 팩토리 메소드를 사용하려면 static 속성을 사용하면 된다

The definition does not specify the type (class) of the returned object, but rather the class containing the factory method. In this example, the createInstance() method must be a static method. The following example shows how to specify a factory method: 

<bean id="clientService"
    class="examples.ClientService"
    factory-method="createInstance"/>

사용방식

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}

 세부 종속성 및 구성을 참조

 

 

 

 

Instantiation by Using an Instance Factory Method

static factory method 를 통한 인스턴스화와 비슷하다

비정적인 메소드를 호출하여 새로운 빈을 생성한다

 leave the class attribute empty and, in the factory-bean attribute, specify the name of a bean in the current (or parent or ancestor) container that contains the instance method that is to be invoked to create the object.

 

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

해당 클래스

public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

 

자주 보던 방식ㅎㅎ

 

당연히 두개 이상도 가능하다

 

 

<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

<bean id="accountService"
    factory-bean="serviceLocator"
    factory-method="createAccountServiceInstance"/>
public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    private static AccountService accountService = new AccountServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }

    public AccountService createAccountServiceInstance() {
        return accountService;
    }
}

이 접근 방식은 팩토리 빈 자체가 DI 관리 구성이 가능하다 Dependencies and Configuration in Detail.

 

In Spring documentation, "factory bean" refers to a bean that is configured in the Spring container and that creates objects through an instance or static factory method. By contrast, FactoryBean (notice the capitalization) refers to a Spring-specific FactoryBean implementation class.

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

 

 

Determining a Bean’s Runtime Type

 

특정 빈의 런타임 유형은 결정하기 쉽지않다

메타데이터 정의에 지정된 클래스는 초기 클래스 참조이고, 잠재적으로 선언된 팩터리 메소드와 결합, 또는 FactoryBean 클래스가 되거나, 다른 다른 런타임 유형으로 이어지기도 한다. 또 아예 전혀 설정이 되지 않을 수도 있다. (which is resolved via the specified factory-bean name instead) 

AOP proxying may wrap a bean instance with an interface-based proxy with limited exposure of the target bean’s actual type (just its implemented interfaces).

 

 

 

특정 bean 의 실제 런타임 유형을 찾는 추천 방법은 지정된 bean 이름에 대한 BeanFactory.getType 을 부르는 것이고

이를 고려하여 동일한 빈 이름에 대해 객체유형을 반환한다. (BeanFactory.getBean)

 

 

콩공장.콩타입가져오기

콩공장.콩가져오기

 

728x90