실습 3일차_@Required

 

@Required Annotation은 Spring 2부터 제공되며, 필수 Property를 명시할 때 사용된다. 

필수 Property를 지정하려면 먼저 Property 설정 Method에 @Required Annotation을 붙여야 한다.

 

 Spring @Required

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		UserService service = ctx.getBean("service", UserService.class);
		System.out.printf("service: %s", service);

		UserService service2 = ctx.getBean("service2", UserService.class);
		System.out.printf("service2: %s", service2);
		
	}
}

UserService.java

package com.service;

import org.springframework.beans.factory.annotation.Required;

public class UserService {
	
	String mesg; // null

	// setter 메서드 주입
	@Required // 넣어줘야 에러 안 뜸
	public void setMesg(String mesg) {
		this.mesg = mesg;
	}

	@Override
	public String toString() {
		return "UserService [mesg=" + mesg + "]";
	}
}

user.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- @ 어노테이션 활성화 -->
	<context:annotation-config />

	<bean id="service" class="com.service.UserService" />
	
	<bean id="service2" class="com.service.UserService">
		<property name="mesg" value="helloworld" />
	</bean>
	
</beans>

 

<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

 

* 출력 화면 

 

 출처

 

@Required : https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=rex4314&logNo=158814986 

+ 강의 교재

 

+ Recent posts