웹사이트 검색

스프링 주석


Spring Annotations를 사용하면 Java 프로그램을 통해 종속성을 구성하고 종속성 주입을 구현할 수 있습니다.

스프링 주석

  • Spring 프레임워크는 IOC(제어 역전) 또는 DI(종속성 주입) 원칙을 구현 및 촉진하며 사실상 IOC 컨테이너입니다.
  • 전통적으로 Spring은 개발자가 XML 기반 구성을 사용하여 빈 종속성을 관리할 수 있도록 합니다.
  • bean과 종속성을 정의하는 다른 방법이 있습니다. 이 방법은 Java 기반 구성입니다.
  • XML 접근 방식과 달리 Java 기반 구성을 사용하면 bean 구성 요소를 프로그래밍 방식으로 관리할 수 있습니다. 이것이 바로 Spring 주석이 도입된 이유입니다.

이 기사에서는 가장 일반적으로 사용되는 Spring Annotation을 살펴보고 몇 가지 예제 프로그램도 살펴볼 것입니다.

스프링 주석 목록

일부 스프링 코어 프레임워크 주석은 다음과 같습니다.

  1. @Configuration: Used to indicate that a class declares one or more @Bean methods. These classes are processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

  2. @Bean: Indicates that a method produces a bean to be managed by the Spring container. This is one of the most used and important spring annotation. @Bean annotation also can be used with parameters like name, initMethod and destroyMethod.

    • name – allows you give name for bean
    • initMethod – allows you to choose method which will be invoked on context register
    • destroyMethod – allows you to choose method which will be invoked on context shutdown

    For example:

    @Configuration
    public class AppConfig {
    
        @Bean(name = "comp", initMethod = "turnOn", destroyMethod = "turnOff")
        Computer computer(){
            return new Computer();
        }
    }
    
    public class Computer {
    
        public void turnOn(){
            System.out.println("Load operating system");
        }
        public void turnOff(){
            System.out.println("Close all programs");
        }
    }
    
  3. @PreDestroy and @PostConstruct are alternative way for bean initMethod and destroyMethod. It can be used when the bean class is defined by us. For example;

     public class Computer {
    
        @PostConstruct
        public void turnOn(){
            System.out.println("Load operating system");
        }
    
        @PreDestroy
        public void turnOff(){
            System.out.println("Close all programs");
        }
    }
    
  4. @ComponentScan: Configures component scanning directives for use with @Configuration classes. Here we can specify the base packages to scan for spring components.

  5. @Component: Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

  6. @PropertySource: provides a simple declarative mechanism for adding a property source to Spring’s Environment. There is a similar annotation for adding an array of property source files i.e @PropertySources.

  7. @Service: Indicates that an annotated class is a “Service”. This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

  8. @Repository: Indicates that an annotated class is a “Repository”. This annotation serves as a specialization of DAO classes.

  9. @Autowired: @Qualifier annotation is used in conjunction with Autowired to avoid confusion when we have two of more bean configured for same type.

스프링 MVC 주석

중요한 Spring MVC 주석 중 일부는 다음과 같습니다.

  1. @컨트롤러
  2. @RequestMapping
  3. @PathVariable
  4. @RequestParam
  5. @ModelAttribute
  6. @ResponseBody
  7. @ResponseHeader

Spring MVC Tutorial에서 이에 대해 자세히 알아볼 수 있습니다.

스프링 트랜잭션 관리 주석

@Transactional은 스프링 선언적 트랜잭션 관리 주석입니다. 자세한 내용은 Spring MVC Hibernate에서 확인하세요.

스프링 보안 주석

@EnableWebSecurity는 Spring Security 예제와 함께 사용됩니다.

스프링 부트 주석

  1. @SpringBootApplication
  2. @EnableAutoConfiguration

자세한 내용은 Spring Boot 예제를 참조하세요.

스프링 주석 예제

스프링 프레임워크 종속성

Maven 프로젝트를 만들고 Spring Core Framework 종속성을 추가했습니다.

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.journaldev.spring</groupId>
	<artifactId>spring-annotations</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Spring Annotations</name>

	<properties>
		<spring.framework>4.3.0.RELEASE</spring.framework>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.framework}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.framework}</version>
		</dependency>

	</dependencies>

</project>

이것은 우리 프로젝트의 모든 스프링 코어 병을 끌어올 것입니다.

구성 요소 클래스

다음 단계는 구성 요소 클래스를 만드는 것입니다. 여기에서는 하나는 MySQL용이고 다른 하나는 Oracle용인 여러 데이터베이스 구성 요소를 모방하고 있습니다.

package com.journaldev.drivers;

public interface DataBaseDriver {
    public String getInfo();
}

DataBaseDriver는 우리가 구현할 기본 인터페이스입니다.

package com.journaldev.drivers;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:mysqldatabase.properties")
public class MySqlDriver implements DataBaseDriver {

    @Value("${databaseName}")
    private String databaseName;
    @Value("${disableStatementPooling}")
    private String disableStatementPooling;

    public String getInfo() {
        return "[ Driver: mySql" +
                ", databaseName: " + databaseName +
                ", disableStatementPooling: " + disableStatementPooling +
                " ]";
    }
}

@Component 주석을 사용하여 이 클래스를 구성 요소로 취급하는 스프링 프레임워크를 나타냅니다. 우리는 또한 @PropertySource@Value 주석을 사용하고 있으며 Spring은 런타임 시 이를 사용하여 지정된 속성 파일에서 이러한 변수 값을 주입하고 설정합니다. 아래는 mysqldatabase.properties 파일에 선언된 속성들이다.

databaseName=school
disableStatementPooling=true
package com.journaldev.drivers;

public class OracleDriver implements DataBaseDriver {

    protected String url;
    protected String user;
    protected String password;
    protected String driver;
    protected Integer port;


    public String getUrl() {
        return url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getInfo() {
        return "[ Driver: Oracle" +
                ", url: " + url +
                ", port; " + port +
                ", user: " + user +
                ", password: " + password  +
                ", driver: " + driver +
                " ] ";
    }
}

OracleDriver는 단순한 빈이며 서비스 클래스를 사용하여 이 빈에 속성을 주입합니다.

스프링 서비스 클래스

package com.journaldev.service;

import com.journaldev.drivers.DataBaseDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    @Qualifier("oracleDriver")
    private DataBaseDriver dataBaseDriver;

    public String getDriverInfo(){
        return dataBaseDriver.getInfo();
    }
}

여기에서 @Service 주석을 사용하여 Spring 프레임워크가 이것을 Service 클래스로 취급하도록 지정합니다. 그런 다음 @Autowired@Qualifier(\oracleDriver\) 주석을 사용하여 스프링 프레임워크에 oracleDriver라는 빈을 클래스 속성 dataBaseDriver. 우리는 아직 이 스프링 빈을 생성하지 않았습니다.

봄콩

마지막 단계는 스프링 빈과 구성 클래스를 생성하여 모든 것을 함께 붙이는 것입니다.

package com.journaldev.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.journaldev.drivers.DataBaseDriver;
import com.journaldev.drivers.MySqlDriver;
import com.journaldev.drivers.OracleDriver;

@Configuration
@ComponentScan("com.journaldev")
@PropertySource("classpath:oracledatabase.properties")
public class AppConfig {

	@Autowired
        Environment environment;
	
	@Bean
	DataBaseDriver oracleDriver() {
        OracleDriver oracleDriver = new OracleDriver();
	oracleDriver.setDriver(environment.getProperty("db.driver"));
        oracleDriver.setUrl(environment.getProperty("db.url"));
        oracleDriver.setPort(Integer.parseInt(environment.getProperty("db.port")));
        oracleDriver.setUser(environment.getProperty("db.user"));
        oracleDriver.setPassword(environment.getProperty("db.password"));

        return oracleDriver;

	}

	@Bean
	DataBaseDriver mysqlDriver() {
		return new MySqlDriver();
	}
}

oracleDriver에 대한 bean 정의를 주목하십시오. 이 메서드에서는 Spring 프레임워크에 의해 environment 변수로 설정되는 oracledatabase.properties 파일에서 속성을 읽습니다. 다음은 oracledatabase.properties 파일에 정의된 속성입니다.

db.url=localhost
db.port=4444
db.user=vasiliy
db.password=yilisav
db.driver=driver_name

스프링 주석 예제 프로젝트를 테스트할 준비가 되었습니다. 요약하자면 다음 단계를 수행했습니다.

  1. maven 프로젝트를 생성하고 필요한 스프링 의존성을 추가했습니다.
  2. 구성 요소 클래스를 생성하고 리소스 파일의 속성을 해당 변수에 삽입했습니다.
  3. 타사 구성 요소가 있는 경우 서비스 클래스를 사용하여 종속성을 주입할 수 있습니다. UserService 클래스를 통해 OracleDriver에 대해 수행한 것과 같습니다.
  4. 마지막으로 Spring Bean을 정의하기 위해 Configuration 클래스를 생성하고 Spring 구성 요소 클래스를 스캔하고 구성하도록 기본 패키지를 설정했습니다.

스프링 주석 예제 테스트

다음은 Spring 주석 예제 프로젝트를 테스트하는 기본 클래스입니다.

package com.journaldev;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.journaldev.config.AppConfig;
import com.journaldev.drivers.DataBaseDriver;
import com.journaldev.service.UserService;

public class Main {
	public static void main(String[] args) {
	AbstractApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.class);

	DataBaseDriver oracle = appContext.getBean("oracleDriver", DataBaseDriver.class);
	DataBaseDriver mysql = appContext.getBean("mysqlDriver", DataBaseDriver.class);
		
        System.out.println("Oracle driver info:");
        System.out.println(oracle.getInfo());
        
        System.out.println("MySQL driver info:");
        System.out.println(mysql.getInfo());

        System.out.println("UserService Information");
	UserService userService = appContext.getBean(UserService.class);
	System.out.println(userService.getDriverInfo());

	appContext.close();
	}
}

다운로드 Spring Annotations 예제 프로젝트 다운로드

참조: API 문서