본문 바로가기

Web/spring

[Annotation] Spring Core Annotations

728x90

https://www.baeldung.com/spring-core-annotations

 

 


 

 

org.springframework.beans.factory.annotation and org.springframework.context.annotation packages.

 

 

 

* DI 관련 주석

 

@Autowired

We can use the @Autowired to mark a dependency which Spring is going to resolve and inject. 

 

생성자주입:

class Car {
    Engine engine;

    @Autowired
    Car(Engine engine) {
        this.engine = engine;
    }
}

 

Setter injection:

class Car {
    Engine engine;

    @Autowired
    void setEngine(Engine engine) {
        this.engine = engine;
    }
}

 

 

Field injection:

class Car {
    @Autowired
    Engine engine;
}

 

 

 

 

@Autowired 에는 기본 boolean 인수가 있다. (default 는 true) 연결하기에 적합한 bean이 없을 경우 true 가 되어 예외처리됨

constructor injection 의 경우 모든 생성자 인수가 필수이다.

 

참고로 4.3부터는 주석을 달 필요가 없다

https://www.baeldung.com/spring-autowire

 

 

 

 

@Bean

bean을 인스턴스화 하는 factory method.

 

@Bean marks a factory method which instantiates a Spring bean:

@Bean
Engine engine() {
    return new Engine();
}

Spring calls these methods when a new instance of the return type is required.

The resulting bean has the same name as the factory method. If we want to name it differently, we can do so with the name or the value arguments of this annotation (the argument value is an alias for the argument name):

@Bean("engine")
Engine getEngine() {
    return new Engine();
}

 

@Bean 애노테이션이 달리려면 @Configuration class 에 있어야한다 << 주의

 

 

 

@Qualifier

We use @Qualifier along with @Autowired to provide the bean id or bean name we want to use in ambiguous situations.

모호한 상황에서의 한정자를 표시할 경우 (동일한 인터페이스를 구현할 때 빈의 이름을 명시적으로 제공하여 구분시킨다)

 

예시

class Bike implements Vehicle {}

class Car implements Vehicle {}


이렇게 같은 인터페이스를 구현해야할 경우에



아래와 같이 @Qualifier 을 적어서 구분시켜준다


@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

@Autowired
void setVehicle(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {
    this.vehicle = vehicle;
}

@Autowired
@Qualifier("bike")
Vehicle vehicle;

 

 

 

 

@Required

Setter method 에서 종속성 표시 할 때 사용

@Required
void setColor(String color) {
    this.color = color;
}

없을 경우 BeanInitializationException 발생

 

 

 

 

 

@Value

injecting property values into beans. 

It's compatible with constructor, setter, and field injection. 

 

// constructor injection
Engine(@Value("8") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

// setter injection
@Autowired
void setCylinderCount(@Value("8") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

// Alternatively
@Value("8")
void setCylinderCount(int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

// Field injection
@Value("8")
int cylinderCount;

 

static values 는 주입 불가능

https://www.baeldung.com/spring-value-annotation

 

 

 

 

 

 

@DependsOn

다른 bean들 보다 먼저 초기화시킬 수 있음

빈 간의 명시적 종속성을 기반으로 자동 수행 됨

for example, JDBC driver loading or static variable initialization.

We can use @DependsOn on the dependent class specifying the names of the dependency beans. 

 

 

@DependsOn("engine")
class Car implements Vehicle {}

 

@Bean 주석 으로 빈을 정의하는 경우 팩토리 메서드에 @DependsOn 주석을 달아야한다

@Bean
@DependsOn("fuel")
Engine engine() {
    return new Engine();
}
복사

 

 

 

@Lazy

bean 을 Lazy 하게 initialize 할 때 사용

애플리케이션 시작 시가 아니라 요청 시 bean을 생성시켜줌

 

배치하는 위치에 따라 다르게 동작한다 <<<< 

This annotation behaves differently depending on where we exactly place it. We can put it on:

  • a @Bean annotated bean factory method, to delay the method call (hence the bean creation)
  • a @Configuration class and all contained @Bean methods will be affected
  • a @Component class, which is not a @Configuration class, this bean will be initialized lazily
  • an @Autowired constructor, setter, or field, to load the dependency itself lazily (via proxy)

 

@Lazy 는 default 가 true 인 value 인수가 있다. (기본 동작을 재정의함)

For example, marking beans to be eagerly loaded when the global setting is lazy, or configure specific @Bean methods to eager loading in a @Configuration class marked with @Lazy:

@Configuration
@Lazy
class VehicleFactoryConfig {

    @Bean
    @Lazy(false)
    Engine engine() {
        return new Engine();
    }
}

For further reading, please visit this article.

 

@Lookup

Spring to return an instance of the method’s return type when we invoke it.

Detailed information about the annotation can be found in this article.

 

 

@Primary

동일한 유형의 여러 bean을 정의해야 할 경우 

모든 연결 지점을 @Qualifier 로 표시 후 필요한 빈의 이름을 지정해주는 방법도 있으나

다른 빈이 거의 필요 없을 경우에 이를 단순화하기 위해 @Primary를 사용함

가장 자주 사용하는 빈에만 @Primary를 표시해주면 규정되지 않은 주입 지점에서 이를 선택한다

 

@Component
@Primary
class Car implements Vehicle {}

@Component
class Bike implements Vehicle {}

@Component
class Driver {
    @Autowired
    Vehicle vehicle;
}

@Component
class Biker {
    @Autowired
    @Qualifier("bike")
    Vehicle vehicle;
}

이렇게 하면 기본 Vehicle 은 Car 로 자동 주입,

아래의 @Qualifier("bike") 의 경우에는 Bike 주입

 

 

@Scope

@Scope to define the scope of a @Component class or a @Bean definition. It can be either singleton, prototype, request, session, globalSession or some custom scope.

지정 범위를 정의함

 

@Component
@Scope("prototype")
class Engine {}

 


Context Configuration Annotations

(여기는 간단히 예시만 정리)

 

 

@Profile

If we want Spring to use a @Component class or a @Bean method only when a specific profile is active, we can mark it with @Profile. We can configure the name of the profile with the value argument of the annotation:

@Component
@Profile("sportDay")
class Bike implements Vehicle {}

You can read more about profiles in this article.

 

 

@Import

We can use specific @Configuration classes without component scanning with this annotation. We can provide those classes with @Import‘s value argument:

@Import(VehiclePartSupplier.class)
class VehicleFactoryConfig {}

 

 

 

@ImportResource

We can import XML configurations with this annotation. We can specify the XML file locations with the locations argument, or with its alias, the value argument:

@Configuration
@ImportResource("classpath:/annotations.xml")
class VehicleFactoryConfig {}

 

 

 

 

@PropertySource

With this annotation, we can define property files for application settings:

@Configuration
@PropertySource("classpath:/annotations.properties")
class VehicleFactoryConfig {}

@PropertySource leverages the Java 8 repeating annotations feature, which means we can mark a class with it multiple times:

@Configuration
@PropertySource("classpath:/annotations.properties")
@PropertySource("classpath:/vehicle-factory.properties")
class VehicleFactoryConfig {}

 

 

@PropertySources

We can use this annotation to specify multiple @PropertySource configurations:

@Configuration
@PropertySources({ 
    @PropertySource("classpath:/annotations.properties"),
    @PropertySource("classpath:/vehicle-factory.properties")
})
class VehicleFactoryConfig {}

Note, that since Java 8 we can achieve the same with the repeating annotations feature as described above.

728x90