@Autowired, CoC ,@Qualifier ,lifecycle

2024. 2. 8. 17:57Daily Codig Reminder

@Autowired

 

coc

String username;
	int age;
	//***************************************************************//
	@Autowired //기본생성자 자동주입 기본은 (required=ture)
	Cat cat; //COC의 개념 , 생성된 bean이 여러개인 경우 변수명과 같은 id의 빈을 자동  주입
	//***************************************************************//
	/*
	 * public void setCat(Cat cat) {
	 * System.out.println("Person.setCat함수호출()========"); this.cat = cat; }
	 */
<context:annotation-config></context:annotation-config>
<bean id="cat" class="com.spring.Cat"><!-- cat == Person의 멤버변수 @Autowired cat -->
	<constructor-arg name="catAge" value="10"></constructor-arg>
	<constructor-arg name="catName" value="뭉크"></constructor-arg>
</bean>
<bean id="pet01" class="com.spring.Cat">
	<constructor-arg name="catAge" value="20"></constructor-arg>
	<constructor-arg name="catName" value="야옹이"></constructor-arg>
</bean>
<bean id="onePerson" class="com.spring.Person">
	<property name="username" value="홍길동"></property>
	<property name="age" value="10"></property>
<!-- 	<property name="cat" ref="pet01"></property> -->
 </bean>

 

@Qualifier

<context:annotation-config></context:annotation-config>
  <bean class="com.spring.Cat" id ="pet01" >
<constructor-arg name="catName" value="야옹이"></constructor-arg>
<constructor-arg name="catAge" value="20"></constructor-arg>
</bean>

  <bean class="com.spring.Cat" id ="pet02" >
<constructor-arg name="catName" value="쿵크"></constructor-arg>
<constructor-arg name="catAge" value="10"></constructor-arg>
</bean>

<bean class="com.spring.Person" id="person">
<property name="username" value="홍길동"></property>
<property name="age" value="10"></property>
</bean>

 

 

String username;
	int age;
@Autowired //기본생성자 자동주입 기본은 (required=ture)
	@Qualifier("pet01")  //autowired와 같이 사용, 특정 bean id지정
//	@Qualifier(value = "pet01")  //특정 bean id지정
	Cat cat; //COC의 개념 , 생성된 bean이 여러개인 경우 변수명이 같은 ref를 주입
	//***************************************************************//
	/*

 

출력문

2.xml에서 빈 생성 , 생성 빈 사용 방법=========
기본생성자 호출=================
com.spring.Person@332796d3

 

 

@Resource

dependency

<!-- dependency 추가시작 부분 -->
<dependency>

<groupId>javax.annotation</groupId>

<artifactId>javax.annotation-api</artifactId>

<version>1.3.1</version>

</dependency>

 

@Resource

@Resource  //set함수를 통해 하나의 객체를 주입받음, 여러개 객체의 경우 에러 
		Cat cat;

 

<bean id="aa" class="com.spring.Cat">
	<constructor-arg name="catAge" value="20"></constructor-arg>
	<constructor-arg name="catName" value="야옹이"></constructor-arg>
</bean>
<!-- Cat객체가 하나인 경우 하나를 주입 받음, 여러개인 경우 에러가 남 -->
<!-- <bean id="pet02" class="com.spring.Cat">
	<constructor-arg name="catAge" value="10"></constructor-arg>
	<constructor-arg name="catName" value="뭉크"></constructor-arg>
</bean> -->
<bean id="onePerson" class="com.spring.Person">
	<property name="username" value="홍길동"></property>
	<property name="age" value="10"></property>
<!-- 	<property name="cat" ref="pet01"></property> -->
 </bean>

cat bean 주입 하지 않아도 @Resource 로 주입 가능

 

출력문

2.xml에서 빈 생성 , 생성 빈 사용 방법=========
기본생성자 호출=================
com.spring.Person@5ce8d869

 

 

name

@Resource(name = "pet02")  //bean id=pet02이용 @Autowire @Qualifire("pet02")
	//여러개 중 bean의 id 지정 주입
	Cat cat;

 

<!-- 주의 annotation사용시 context:annotation-config필요함 -->
<context:annotation-config></context:annotation-config>


<bean id="pet01" class="com.spring.Cat"><!-- cat == Person의 멤버변수 @Autowired cat -->
	<constructor-arg name="catAge" value="20"></constructor-arg>
	<constructor-arg name="catName" value="야옹이"></constructor-arg>
</bean>
<bean id="pet02" class="com.spring.Cat">
	<constructor-arg name="catAge" value="10"></constructor-arg>
	<constructor-arg name="catName" value="뭉크"></constructor-arg>
</bean>
<bean id="onePerson" class="com.spring.Person">
	<property name="username" value="홍길동"></property>
	<property name="age" value="10"></property>
<!-- 	<property name="cat" ref="pet01"></property> -->
 </bean>

property name : pet01로 주입

 

 

COC

@Resource  //Coc개념사용
		Cat cat;

 

<context:annotation-config></context:annotation-config>

<bean id="cat" class="com.spring.Cat"><!-- CoC 동일한 id= 멤버변수-->
	<constructor-arg name="catAge" value="20"></constructor-arg>
	<constructor-arg name="catName" value="야옹이"></constructor-arg>
</bean>
<bean id="pet02" class="com.spring.Cat">
	<constructor-arg name="catAge" value="10"></constructor-arg>
	<constructor-arg name="catName" value="뭉크"></constructor-arg>
</bean>
<bean id="onePerson" class="com.spring.Person">
	<property name="username" value="홍길동"></property>
	<property name="age" value="10"></property>
<!-- 	<property name="cat" ref="pet01"></property> -->
 </bean>

 

 

method

 

Cat cat;
	//Cat cat1; 
	//***************************************************************//
		@Resource  //@Resource위치가 set함수에 사용됨
		//함수이름을 setPet으로 변경하고 id="pet"을 사용하게 됨

 

 

<context:annotation-config></context:annotation-config>

<bean id="pet" class="com.spring.Cat"><!-- CoC 동일한 id= 멤버변수-->
	<constructor-arg name="catAge" value="20"></constructor-arg>
	<constructor-arg name="catName" value="야옹이"></constructor-arg>
</bean>
<bean id="pet02" class="com.spring.Cat">
	<constructor-arg name="catAge" value="10"></constructor-arg>
	<constructor-arg name="catName" value="뭉크"></constructor-arg>
</bean>
<bean id="onePerson" class="com.spring.Person">
	<property name="username" value="홍길동"></property>
	<property name="age" value="10"></property>
<!-- 	<property name="cat" ref="pet01"></property> -->
 </bean>

 

 

@Autowired_resource

main

GenericXmlApplicationContext ctx=
				new GenericXmlApplicationContext("classpath:com/config/config.xml");
		DeptService service= ctx.getBean("deptService",DeptService.class);
		List<String> list= service.getList();
		for (String s : list) {
			System.out.println(s);
		}

 

dao

public List<String> getList() {
		// TODO Auto-generated method stub
		return Arrays.asList("A","B","C");

 

service

@Resource(name="ddd")/////////////////////////////////////// byname
	DeptDAO dao;
	public DeptDAO getDao() {
		return dao;
	}
	public void setDao(DeptDAO dao) {
		this.dao = dao;
	}
	public DeptService() {
			//dao= new DeptDAO();	
	}
	public List<String> getList(){
		return dao.getList();
	}

 

bean

<context:annotation-config></context:annotation-config>
<!-- annotation지정을 위해 필수 -->
<bean id="ddd" class="com.dao.DeptDAO"></bean>
<bean id="deptService" class="com.service.DeptService"></bean><!-- dao자동주입 -->

 

 

 

@Value, SpEL

 

jdbc.properties 4가지 정보

user.oracle = 드라이버 정보

user.id =sccot

//기존방법

 

bean

<context:annotation-config></context:annotation-config>

<bean class="com.spring.Person" id="person"></bean>

</beans>

 

person.java

@Value("홍길동") //peoperty name ="username" value ="홍길동
	String username;
	@Value("10")
	int age;

출력:

Person [username=홍길동, age=10]

 

<context:annotation-config></context:annotation-config>
<context:property-placeholder location="classpath:com/spring/test.properties"/>
<bean class="com.spring.Person" id="person">
<property name="username" value="${value.name}"></property>
<property name="age" value="${value.age}"></property>
</bean>

properties

value.name=\uD64D\uAE38\uB3D9
value.age=20

출력:

Person [username=홍길동, age=10]

 

@Value("#{yyy.username}") //peoperty name ="username" value ="홍길동
	String username;
	@Value("#{yyy.age}")
	int age;

 

bean

<context:annotation-config></context:annotation-config>
<bean class="com.spring.Person" id="yyy">
<constructor-arg name="username" value="홍길동"></constructor-arg>
<constructor-arg name="age" value="10"></constructor-arg>
</bean>

<bean class="com.spring.Person" id="xxx">
</bean>
</beans>

 

 

이거도 됨

@Value("${value.name}") //peoperty name ="username" value ="홍길동
	String username;
	@Value("${value.age}")
	int age;

 

 

<context:annotation-config></context:annotation-config>
<bean class="com.spring.Person" id="yyy">
<constructor-arg name="username" value="홍길동"></constructor-arg>
<constructor-arg name="age" value="10"></constructor-arg>
</bean>

<bean class="com.spring.Person" id="xxx">
<property name="username" value="#{yyy.username}"></property>
<property name="age" value="#{yyy.age}"></property>
</bean>

// @Value("${yyy.name}")

//peoperty name ="username"

value ="홍길동

String username;

// @Value("${yyy.age}")

 

<context:annotation-config></context:annotation-config>


<bean class="com.spring.Person" id="xxx">
<property name="username" value="#{'이순신'}"></property>
<property name="age" value="#{44+1}"></property>
<property name="married" value="#{not (3>2)}"></property>
<property name="weight" value="#{72.6}"></property>
</bean>

<bean class="com.spring.Person" id="xxx2">
<property name="username" value="홍길동"></property>
<property name="age" value="20"></property>
<property name="married" value="false"></property>
<property name="weight" value="72.4"></property>
</bean>

Person [username=홍길동, age=20, isMarried=false, weight=72.4]

 

<bean class="com.spring.Person" id="onePerson">
<property name="username" value="홍길동"></property>
<property name="age" value="10"></property>
<!-- value="#{pet01}" == ref="pet01"-->
<property name="cat" value="#{pet01}"></property>
</bean>

 

 

<bean id="xxx" class="com.spring.Person">
<property name="username" value="유관순"></property>
</bean>
<bean class="com.spring.Person" id="onePerson">
<property name="username" value="#{xxx.username}"></property>
<property name="age" value="10"></property>
<property name="cat" value="#{pet01}"></property>
</bean>

Person [username=유관순, age=10, cat=Cat [catName=야옹이, catAge=10]]

<property name="username" value="#{xxx.getXXX()}"></property>
public String getXXX() {
		return this.getUsername();
	}

Person [username=유관순, age=10, cat=Cat [catName=야옹이, catAge=10]]

 

 

 

bean 자동생성

<!-- context check
클래스에 달린 @Componenet 를 자동으로 bean 생성함
annotaion-config 포함됨 
com.sercice 패키지 기분 하위패키지 검색-->
<context:component-scan base-package="com.service"/>
</beans>

@Component 로 bean 생성

//@Component // id -> deptService
@Component("test")
public class DeptService { // id -> deptService
	public DeptService () {
		System.out.println("DeptService 기본생성자 호츨");
	}
		public String getService() {

	return "DeptService.getService() 호출됨";
}

Test.java

ApplicationContext ctx = new
				GenericXmlApplicationContext("classpath:com/spring/config.xml");
		DeptService service = ctx.getBean("test", DeptService.class);
		System.out.println(service);
		System.out.println(service.getService());
		DeptService2 service2 = ctx.getBean("xxx", DeptService2.class);//id 지정안하면 위랑 똑같이 나옴
System.out.println(service2);
System.out.println(service2.getService());

DeptService 기본생성자 호츨

DeptService 기본생성자 호츨

com.service.DeptService@e57b96d

DeptService.getService() 호출됨

com.service.DeptService2@32c726ee

DeptService.getService() 호출됨

 

bean

 

<context:component-scan base-package="com.*"/>
</beans>

 

 

Test

ApplicationContext ctx = new
				GenericXmlApplicationContext("classpath:com/spring/config.xml");
		DeptDAO dao = ctx.getBean("dao", DeptDAO.class);
		System.out.println(dao.getInfo());
		DeptService service = ctx.getBean("deptService", DeptService.class);
		System.out.println(service.getInfo());
	}

 

dao↓

@Repository("dao")
public class DeptDAO {
	public DeptDTO getInfo() {
        return new DeptDTO(100, "관리", "서울");
    }

	public DeptDAO() {
		super();
		System.out.println("dao 기본생성자");
	}

 

service ↓

@Service
@Scope(value="singleton")
public class DeptService { // id -> deptService
	@Autowired
	DeptDAO dao;

public DeptDAO getDao() {
		return dao;
	}

	public void setDao(DeptDAO dao) {
		this.dao = dao;
	}

public DeptService() {
	System.out.println("Service 기본생성자");
}
public DeptDTO getInfo() {
	return dao.getInfo();
}

 

dao 기본생성자

Service 기본생성자

DeptDTO [deptno=100, dname=관리, loc=서울]

DeptDTO [deptno=100, dname=관리, loc=서울]

 

<context:component-scan base-package="com.*"/>

<bean id="echoBean" class="com.bean.EchoBean">
<property name="one" ref="xxx"> </property>
<property name="two" ref="twoService"></property>
</bean>

oneservice

@Service("xxx")

public class OneService { // id -> deptService
public void one () {
	System.out.println("OneService");
}

twoService

@Service

public class TwoService { // id -> deptService
public void two () {
	System.out.println("TwoService");
}

 

 

 

bean 생성안하고 주소 뽑기

<context:component-scan base-package="com.*"/>
@Component
public class EchoBean {
	@Autowired
OneService one;
	@Autowired
TwoService two;
public OneService getOne() {
	return one;
}
public void setOne(OneService one) {
	this.one = one;
}
public TwoService getTwo() {
	return two;
}
public void setTwo(TwoService two) {
	this.two = two;
}

 

 

lifecycle

package com.dto;
//@Alias("별칭")


public class Student {
	private String name;
private int age; 

public void getInfo() {
	System.out.println("getInfo==========");
}
public void aaa() {
	System.out.println("init-method.aaa");
}
public void bbb () {
	System.out.println("destroy -method.bbb");
}
public Student() {
	System.out.println("기본생성자 호출");
}
}

Test -제너릭 써야함

GenericXmlApplicationContext ctx = new
				GenericXmlApplicationContext("classpath:com/spring/echo.xml");
		Student student = ctx.getBean("aaa", Student.class);
		System.out.println(student);
		student.getInfo();
		ctx.close();

	}

bean

<bean class="com.dto.Student" id="aaa" init-method="aaa" destroy-method="bbb"></bean>

기본생성자 호출

init-method.aaa

com.dto.Student@3f9342d4

getInfo==========

destroy -method.bbb

 

bean

<bean class="com.dto.Student" ></bean>
package com.dto;
//@Alias("별칭")

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Student implements InitializingBean, DisposableBean {
	private String name;
private int age; 

public void getInfo() {
	System.out.println("getInfo==========");
}
//public void aaa() {
//	System.out.println("init-method.aaa");
//}
//public void bbb () {
//	System.out.println("destroy -method.bbb");
//}
public Student() {
	System.out.println("기본생성자 호출");
}
@Override
public void destroy() throws Exception {
	// TODO Auto-generated method stub
	
}
@Override
public void afterPropertiesSet() throws Exception {
	// TODO Auto-generated method stub
	
}
}

기본생성자 호출

com.dto.Student@4b40f651

getInfo==========

 

annotation 쓰기 위해 dependency 추가

<context:annotation-config></context:annotation-config>
<bean class="com.dto.Student" id="stu" ></bean>
<!-- 클래스에서 직접 구현 -->
</beans>
package com.dto;
//@Alias("별칭")

import javax.annotation.PostConstruct;

public class Student {
	private String name;
private int age; 

public void getInfo() {
	System.out.println("getInfo==========");
}
@PostConstruct
public void aaa() {
	System.out.println("init-method.aaa");
}
@PostConstruct
public void bbb () {
	System.out.println("destroy -method.bbb");
}
public Student() {
	System.out.println("기본생성자 호출");
}

}
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

'Daily Codig Reminder' 카테고리의 다른 글

mybatis  (1) 2024.02.12
spring- jdbc  (1) 2024.02.08
props, autowired  (1) 2024.02.07
spring - property  (1) 2024.02.06
스프링 준비  (0) 2024.02.05