Spring의 Bean 획득 방법에 대한 자세한 설명
Spring 프레임워크에서 Bean 획득은 매우 중요한 부분입니다. 애플리케이션에서는 종속성 주입을 사용하거나 Bean 인스턴스를 동적으로 획득해야 하는 경우가 많습니다. 이 기사에서는 Spring에서 Bean을 얻는 방법을 자세히 소개하고 구체적인 코드 예제를 제공합니다.
- @Component 주석을 통해 Bean 가져오기
@Component 주석은 Spring 프레임워크에서 일반적으로 사용되는 주석 중 하나입니다. 클래스에 @Component 주석을 추가하여 Bean으로 식별하고 ApplicationContext를 사용하여 컨테이너에서 Bean의 인스턴스를 얻을 수 있습니다. 예는 다음과 같습니다.
@Component public class UserService { // ... } public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); UserService userService = context.getBean(UserService.class); // ... } }
- @Autowired 주석을 통해 Bean 가져오기
@Autowired 주석은 Spring 프레임워크에서 일반적으로 사용되는 또 다른 주석입니다. @Autowired 주석을 멤버 변수에 추가함으로써 Spring은 일치하는 Bean을 이 변수에 자동으로 주입합니다. 예는 다음과 같습니다.
@Component public class UserService { @Autowired private UserRepository userRepository; // ... } public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); UserService userService = context.getBean(UserService.class); // ... } }
- @Qualifier 주석을 통해 Bean 가져오기
@Autowired 주석을 사용할 때 컨테이너에 일치하는 Bean이 여러 개 있으면 Spring은 어떤 Bean을 주입할지 결정할 수 없습니다. 이때 @Qualifier 어노테이션을 사용하여 주입할 Bean의 이름을 지정할 수 있습니다. 예는 다음과 같습니다.
@Component public class UserService { @Autowired @Qualifier("userRepositoryImpl") private UserRepository userRepository; // ... } public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); UserService userService = context.getBean(UserService.class); // ... } }
- @Bean 주석을 통해 Bean 가져오기
주석을 사용하여 Bean을 추가하는 것 외에도 @Configuration 및 @Bean 주석을 사용하여 Bean을 생성할 수도 있습니다. @Configuration 주석이 달린 클래스는 Spring 컨테이너에 의해 구성 클래스로 인식되며 @Bean 주석은 Bean 인스턴스를 생성하기 위해 구성 클래스에서 사용됩니다. 예는 다음과 같습니다.
@Configuration public class AppConfig { @Bean public UserService userService() { return new UserService(); } } public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); UserService userService = context.getBean(UserService.class); // ... } }
- XML 구성 파일을 통해 Bean 가져오기
주석을 사용하는 것 외에도 XML 구성 파일을 사용하여 Bean을 가져올 수도 있습니다. XML 구성 파일에서 Bean의 이름, 유형 및 속성을 정의하고 ApplicationContext를 통해 구성 파일을 로드하여 Bean 인스턴스를 얻을 수 있습니다. 다음은 예입니다.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userService" class="com.example.UserService"> <property name="userRepository" ref="userRepositoryImpl" /> </bean> <bean id="userRepositoryImpl" class="com.example.UserRepositoryImpl" /> </beans>
public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = context.getBean("userService", UserService.class); // ... } }
위는 Spring에서 Bean을 얻는 몇 가지 일반적인 방법입니다. @Component, @Autowired, @Qualifier, @Bean 및 XML 구성 파일을 사용하면 애플리케이션에 필요한 Bean 인스턴스를 쉽게 얻을 수 있습니다. 다양한 시나리오에서 빈을 얻기 위한 적절한 방법을 선택할 수 있으며 Spring의 종속성 주입 메커니즘은 코드를 더욱 간결하고 유연하며 테스트 가능하게 만들 수 있습니다.
위 내용은 Spring의 Bean 획득 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기
