Spring 실습 1일차_Bean Create

 

 Bean Create

Main.java

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

public class Main {
	public static void main(String[] args) {
		
		// IoC 컨테이너 생성 ==> XXXXApplicationContext	
		ApplicationContext ctx = new GenericXmlApplicationContext("user.xml");
		
		// 생성된 빈 접근
		UserService service = ctx.getBean("service", UserService.class);
		System.out.println(service.getMesg());
	}
}

UserDAO.java

package com.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.service.UserService;

public class UserDAO {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	public UserDAO() {
		logger.info("UserDAO 생성자");
	}
}

UserService.java

package com.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// POJO Class
public class UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	public UserService() {
		logger.info("UserService 생성자");
	}
	
	// 메서드 추가
	public String getMesg() {
		return "UserService";
	}
}

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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- bean 등록  (/:empty tag) -->
	<bean id="service" class="com.service.UserService" />
	<bean id="dao" class="com.dao.UserDAO"/>
</beans>

 

* Console 출력값 : 

 

Bean Create_Pakage 추가

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {

	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("com/config/user.xml");
	}
}

UserService.java

package com.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// POJO Class
public class UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	public UserService() {
		logger.info("UserService 생성자");
	}
	
	// 메서드 추가
	public String getMesg() {
		return "UserService";
	}
}

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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- bean 등록  (/:empty tag) -->
	<bean id="service2" class="com.service.UserService" />
</beans>

 

 출처

 

 

+ 강의 교재

+ Recent posts