이안의 평일코딩

Spring 4일차 - Autowired 본문

Back-end/Spring

Spring 4일차 - Autowired

이안92 2020. 10. 23. 10:02
반응형

2020.10.23(금)

src/main/java

Config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
   "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <typeAliases>
  <typeAlias type="com.sist.di.MusicVO" alias="MusicVO"/>
 </typeAliases>
 <mappers>
  <mapper resource="com/sist/di/music-mapper.xml"/>
 </mappers>
</configuration>

app.xml(beans, context, p) => Spring Bean Configuration File

<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	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">
	<!-- 데이터베이스 정보 생성 : BasicDataSource -->
	<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
		p:driverClassName="oracle.jdbc.driver.OracleDriver"
		p:url="jdbc:oracle:thin:@211.238.142.000:1521:XE"
		p:username="hr"
		p:password="happy"
	/>
	<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="ds"
		p:configLocation="classpath:Config.xml"
	/>
	<!-- classpath: src/main/java /WEB-INF/ -->
	<!-- MyBatis에 전송 getConnection, disConnection -->
	<!-- DAO전송 : 활용 -->
	<bean id="dao" class="com.sist.di.MusicDAO"
		p:sqlSessionFactory-ref="ssf"
	/>
</beans>

 

src/main/java

com.sist.di

MusicVO.java

package com.sist.di;

public class MusicVO {
	private String title;
	private String singer;
	private String album;
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getSinger() {
		return singer;
	}
	public void setSinger(String singer) {
		this.singer = singer;
	}
	public String getAlbum() {
		return album;
	}
	public void setAlbum(String album) {
		this.album = album;
	}	
}

music-mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sist.di.music-mapper">
	<select id="musicAllData" resultType="MusicVO">
		SELECT title,singer,album 
		FROM genie_music
	</select>
</mapper>

MusicDAO.java (DAO받을때 상속 SqlSessionDaoSupport)

package com.sist.di;

import org.mybatis.spring.support.SqlSessionDaoSupport;

/*
 * 	1. XML이용
 * 	2. Annotation
 *  3. XML+Annotation(***)
 *  4. 순수 자바 (차세대) = 스프링5에서 주로 사용
 */

/*
 * <select id="musicAllData" resultType="MusicVO">
		SELECT title,singer,album 
		FROM genie_music
	</select>
 */
import java.util.*; // 자료가 많으니 array로 가져옴
public class MusicDAO extends SqlSessionDaoSupport{
	public List<MusicVO> musicAllData(){
		return getSqlSession().selectList("musicAllData");
	}
	/*
	 * SqlSession session=ssf.openSession();
	 * list=session.selectList("");
	 * session.close();
	 * return list;
	 * ==> 반복 제거 ==> 소스 간결
	 * 프로그램
	 * 	  = 공통 모듈 => AOP
	 *    = 핵심 모듈
	 *    공통 => 싱글턴
	 *    생성 == 소멸 담당 => 객체 생명주기
	 *    생성 constructorDI -> setterDI -> method -> 프로그래머가 활용 -> method -> 소멸
	 *    ===							init-method						destroy-method
	 *    new 클래스명()
	 *    
	 *    DI, AOP
	 *    ======= 라이브러리 (MVC)
	 */
}

MainClass.java

package com.sist.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.*;
public class MainClass {

	public static void main(String[] args) {
		ApplicationContext app=new ClassPathXmlApplicationContext("app.xml");
		MusicDAO dao=(MusicDAO)app.getBean("dao");
		//MusicDAO dao=new MusicDAO();
		List<MusicVO> list=dao.musicAllData();
		for(MusicVO vo : list) {
			System.out.println(vo.getTitle()+"-"
					+vo.getSinger()+"-"
					+vo.getAlbum());
		}
	}
}

 


 

src/main/java

app2.xml(beans, context)

<?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:component-scan base-package="com.sist.di2"/>
	<!-- 
	메모리 할당
	@Component, @Repository, @Service, @Controller, @RestController
	Inject
	@Required, @Autowired, @PostConstruct, @PreDestroy, @Resource
	 -->
</beans>

src/main/java

com.sist.di2

Saram.java

package com.sist.di2;

import org.springframework.stereotype.Component;

// 메모리 할당
@Component
// <bean> (X)
public class Saram {
	private String name="홍길동";
	private String sex="남자";
	private int age=30;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

 

Sawon.java

package com.sist.di2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//메모리 할당
@Component
public class Sawon {
	//자동 주입
	@Autowired
	private Saram saram; // (Saram)app.getBean("saram")
	private String dept="개발부";
	private String job="대리";
	public Saram getSaram() {
		return saram;
	}
	public void setSaram(Saram saram) {
		this.saram = saram;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
}

 

MainClass.java

package com.sist.di2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
/*
 * 	class BoardDAO => boardDAO (default ID)
 * 	==> Sawon sawon=new Sawon()
 * 		Saram saram=new Saram()
 */
@Component
public class MainClass {
	// 지역변수는 사용이 불가능
	@Autowired
	private Sawon sa; //null
	public static void main(String[] args) {
		ApplicationContext app=new ClassPathXmlApplicationContext("app2.xml");
		MainClass mc=(MainClass)app.getBean("mainClass");
		System.out.println("이름:"+mc.sa.getSaram().getName());
		System.out.println("성별:"+mc.sa.getSaram().getSex());
		System.out.println("나이:"+mc.sa.getSaram().getAge());
		System.out.println("부서:"+mc.sa.getDept());
		System.out.println("직위:"+mc.sa.getJob());
	}
}

 


 

 

src/main/java

Config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
   "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <typeAliases>
  <typeAlias type="com.sist.di.MusicVO" alias="MusicVO"/>
 </typeAliases>
 <mappers>
  <mapper resource="com/sist/di/music-mapper.xml"/>
 </mappers>
</configuration>

 

src/main/java

com.sist.di

MusicVO.java

package com.sist.di;

public class MusicVO {
	private String title;
	private String singer;
	private String album;
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getSinger() {
		return singer;
	}
	public void setSinger(String singer) {
		this.singer = singer;
	}
	public String getAlbum() {
		return album;
	}
	public void setAlbum(String album) {
		this.album = album;
	}
	
}

music-mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sist.di.music-mapper">
	<select id="musicAllData" resultType="MusicVO">
		SELECT title,singer,album 
		FROM genie_music
	</select>
	
</mapper>

MusicDAO.java

package com.sist.di;

import org.mybatis.spring.support.SqlSessionDaoSupport;

/*
 * 	1. XML이용
 * 	2. Annotation
 *  3. XML+Annotation(***)
 *  4. 순수 자바 (차세대) = 스프링5에서 주로 사용
 */

/*
 * <select id="musicAllData" resultType="MusicVO">
		SELECT title,singer,album 
		FROM genie_music
	</select>
 */
import java.util.*; // 자료가 많으니 array로 가져옴
public class MusicDAO extends SqlSessionDaoSupport{
	public List<MusicVO> musicAllData(){
		return getSqlSession().selectList("musicAllData");
	}
	/*
	 * SqlSession session=ssf.openSession();
	 * list=session.selectList("");
	 * session.close();
	 * return list;
	 * ==> 반복 제거 ==> 소스 간결
	 * 프로그램
	 * 	  = 공통 모듈 => AOP
	 *    = 핵심 모듈
	 *    공통 => 싱글턴
	 *    생성 == 소멸 담당 => 객체 생명주기
	 *    생성 constructorDI -> setterDI -> method -> 프로그래머가 활용 -> method -> 소멸
	 *    ===							init-method						destroy-method
	 *    new 클래스명()
	 *    
	 *    DI, AOP
	 *    ======= 라이브러리 (MVC)
	 */
}

MusicModel.java

package com.sist.di;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
//app.getBean()
public class MusicModel {
	@Autowired
	private MusicDAO dao;
	@RequestMapping("music/music.do")
	public String music_music(HttpServletRequest request) {
		MusicDAO dao=new MusicDAO();
		List<MusicVO> list=dao.musicAllData();
		request.setAttribute("list", list);
		return "music/music";
	}
}

 

src/main/webapp/WEB-INF

app.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"
	xmlns:p="http://www.springframework.org/schema/p"
	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">
	<!-- 데이터베이스 정보 생성 : BasicDataSource -->
	<context:component-scan base-package="com.sist.*"/>
	<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
		p:driverClassName="oracle.jdbc.driver.OracleDriver"
		p:url="jdbc:oracle:thin:@211.238.142.000:1521:XE"
		p:username="hr"
		p:password="happy"
	/>
	<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="ds"
		p:configLocation="classpath:Config.xml"
	/>
	<!-- classpath: src/main/java /WEB-INF/ -->
	<!-- MyBatis에 전송 getConnection, disConnection -->
	<!-- DAO전송 : 활용 -->
	<bean id="dao" class="com.sist.di.MusicDAO"
		p:sqlSessionFactory-ref="ssf"
	/>
</beans>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<servlet>
		<servlet-name>aaa</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/app.xml</param-value>
	</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>aaa</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

 


 

src/main/java

app3.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:component-scan base-package="com.sist.di3"></context:component-scan>

</beans>

src/main/java

com.sist.di3

MyDAO.java (interface)

package com.sist.di3;

public interface MyDAO {
	public void getConnection();
	public void disConnection();
}

MySql.java

package com.sist.di3;

import org.springframework.stereotype.Repository;

@Repository
public class MySql implements MyDAO{

	@Override
	public void getConnection() {
		System.out.println("MySql에 연결");
	}

	@Override
	public void disConnection() {
		System.out.println("MySql에 연결 해제");
	}
	
}

Oracle.java

package com.sist.di3;

import org.springframework.stereotype.Repository;

@Repository
public class Oracle implements MyDAO{

	@Override
	public void getConnection() {
		System.out.println("오라클 연결");	
	}

	@Override
	public void disConnection() {
		System.out.println("오라클 해제");
	}

}

MainClass.java

package com.sist.di3;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class MainClass {
	//@Autowired
	//@Qualifier("mySql") mySql, oracle 둘중에 선택
	
	//@Autowired+@Qualifier("oracle") 합치면 => @Resource
	@Resource(name="oracle")
	private MyDAO dao; //mySql, oracle
	// app.getBean("mySql"); ==> instance of
	public static void main(String[] args) {
		ApplicationContext app=new ClassPathXmlApplicationContext("app3.xml");
		MainClass mc=(MainClass)app.getBean("mainClass");
		mc.dao.getConnection();
		mc.dao.disConnection();
		
		
		/*
		 * 	String s => Object속성 갖고있음
		 *  StringBuffer sb => Object속성 갖고있음
		 *  Object obj
		 *  
		 *  instanceof 우변이 크거나 같거나
		 *  
		 *  if(s instanceof String) true
		 *  if(s instanceof Object) true
		 *  if(sb instanceof StringBuffer) true
		 *  
		 *  if(obj instanceof StringBuffer) false
		 *  if(sb instanceof String) error
		 */
		
		String s="Hello";
		StringBuffer sb=new StringBuffer();
		Object obj=new Object();
		if(sb instanceof String) { // 오류
			System.out.println("수행");
		}
	}
}

 

@Autowired : 스프링에 관리할 대상의 클래스 객체를 저장

                       저장된 클래스의 주소값을 스프링에 자동으로 주입(전송)


Component (interface)

package com.sist.di4;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(TYPE)
public @interface Component {

}

 

A.java (@Component)

package com.sist.di4;

@Component
public class A {

}

B.java

package com.sist.di4;

public class B {

}

MainClass.java

package com.sist.di4;
import java.util.*;

import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainClass {
	public static void main(String[] args) {
		try {
			List<String> list=new ArrayList<String>();
			list.add("com.sist.di4.A");
			list.add("com.sist.di4.B");
			/*
			 * @Component, @Repository, @Service, @Controller, @RestController
			 */
			for(String s:list) {
				Class clsName=Class.forName(s);
				if(clsName.isAnnotationPresent(Component.class)==false)
					continue;
				Object obj=clsName.newInstance();
				System.out.println(obj);
			}
		}catch(Exception ex) {}
	}
}

 

=> A만 메모리 할당된다

 

반응형

'Back-end > Spring' 카테고리의 다른 글

Spring 6일차 - ComponentScan  (0) 2020.10.31
Spring 5일차 - Repository  (0) 2020.10.31
Spring 3일차 - Container  (0) 2020.10.22
Spring 2일차 - XML, Configuration  (0) 2020.10.21
Spring 1일차 - DI(Dependency Injection 의존성 주입)  (0) 2020.10.20
Comments