Back to feed
Renewal·서른의 생활코딩

Following Toby's Spring 3.1 in Spring Boot: Ch.1 - 1.5 Spring's IoC

NS
normalstory
cover image

Following Toby's Spring 3.1 in Spring Boot : Chapter 1 Objects and Dependency Relations - 1.5 Spring's IoC

Dev environment 

- OS : mac

- STS : 4.0.1

- MySQL : Server version: 8.0.13 Homebrew

- Framework : keeping it as dependency-free as possible, sticking to jar only.


Related links 

- Spring User Group homepage     http://www.ksug.org/

- Spring User Group Q&A     https://groups.google.com/forum/#!topic/ksug/13vB4tCFqrI

- 2017 Spring Camp                       https://www.youtube.com/playlist?list=PLdHtZnJh1KdZ6NDO9zc9hF4tONDLTSEUV



Chapter 1. Objects and Dependency Relations 

1.5 Spring's IoC

Inversion of Control — a term that's been around well before Spring. Let's use it to improve UserDao a bit further.


1.5.1 Spring IoC via the Object Factory

1. The application context and configuration information 

Right from the start a bunch of terms show up. Similar names, similar functions..Oof, let me sketch it out. 

My figure 3 comparing EJB and Spring beans


For reference, in Toby's book the author says for now you can think of a bean factory and an application context as the same thing. Looking at my figure 4 above, a familiar name shows up — DaoFactory. It's the factory class we built in the previous example. Pull out the configuration info as a separate thing, and that's your application context.

And  the author walks through how to build configuration information for the bean factory and the application context. 

Looking again at the earlier figure: DaoFactory in the example, we separated the component that held the application logic from the factory that served as the blueprint. That "blueprint" is what the application context plus its configuration info is. It doesn't carry application logic itself, but through IoC it takes on responsibilities like creating application components and wiring up relationships between them. Just like a building is constructed by following a blueprint..


2. An application context that uses DaoFactory 

(From here on, the subject is Spring — specifically, Spring's bean factory.)

Let's build the configuration info so Spring's bean factory can use the DaoFactory we wrote earlier.


1) Add annotations @ so Spring can recognize it. 

@configuration    <-  a class that handles configuration for the bean factory 

Applied to 1.) class DaoFactory

@bean                 <- a method that creates an object 

Applied to 1.) userDao() method    : creates and initializes an object of type UserDao and returns it. 

Applied to 2.) connectionMaker() method     : creates an object of type ConnectionMaker. 


(1) Writing the code 


package springbook.user.dao;

/**
 * 토비의 스피링 3.1 예제 따라하기 
 * 1장 - 05 스프링의 IoC - DaoFactory에 설정파일 분리하기
 * 
 * @since 	2019.02.22
 * @author 	친절한 찰쓰씨 http://normalstory.tistory.com
 */
@Configuration 
public class DaoFactory {
	/**
	 * UserDao 타입의 오브젝트를 생성하고 초기화해서 돌려주는 역할 담당 
	 * @return
	 */
	@Bean 
	public UserDao userDao() {
		UserDao userDao = new UserDao(connectionMaker()); 
		return userDao;
	}
	
	/**
	 * ConnectionMaker 타입의 오브젝트를 생성하는 역할 담당 
	 * @return
	 */
	public ConnectionMaker connectionMaker() {
		return new DConnectionMaker();
	}
}

The code we've written has effectively been converted into Spring-specific configuration info, like an XML file. Conceptually, anyway. The file itself is still a class file. 


(2) Adding the library to get rid of the red underlines  

But, the annotations still have red underlines

Since I wrote Spring-specific code, I need to add the Spring libraries. Here's where I don't quite click with the flow. ;D The order of operations isn't obvious. The author sometimes writes the code first then adds the library, sometimes the other way around. (So screenshots may not match the post exactly.. ;>)

  

But I saw errors.. and I had red underlines, so I need to deal with those first. It's a bit long. Also, normally you don't add jar files directly — you use Maven or Gradle. Before Spring Boot Maven seemed more common; after Spring Boot, Gradle. Personally I'll try both later. But I should at least try each once, so this time I'll add jars directly. 


1. Getting the libraries 

Most Spring libraries can be found at https://mvnrepository.com. Steps shown below.

1) Visit the site and search for the library you need.

2) Clicking a search result brings up the detail view. Pick the version you want. Rather than the absolute latest, going with the second-latest or the most-downloaded version tends to be safer.

3) Clicking the version takes you to the download page. You can see: Maven, Gradle, jar, pom — you can get all of them. The site is just named "Maven Repository."

4) Download the files you want like this.  

       (1) Here's the list of 7 files the author said to install. 

             cglib, common-logging, spring asm, spring beans, spring contexts, spring core, spring expression 

       (2) But an error pops up... ㅜㅜ Probably a version mismatch. The message below says AOP is required.

            I went back to the repo, searched for Spring AOP, downloaded it, and added it in.

       (3) Long story short — this is the final bundle.

               

JARs for tobe spring 1.5 spring IoC.zip
Download


2. Applying the libraries 

5) Back to Spring: right-click the project where you want to apply the downloaded jar files.

6) Open Configure Build Path — under the Libraries tab, click the second button on the right: external jars.

7) Select all the downloaded jars.

8) They've been added.

9) After that, it's safer to refresh the project. Right-click the project and the refresh option is in the menu (screenshot omitted). Still, my red underlines didn't disappear. But ~ hover over the red line and a popup layer appears like the capture below. Read carefully and the first item is "import something something". Click that link and the red underlines go away, and the library gets added automatically. 

 The end ~ back to coding ~ 


2) Let's build the application context that uses Spring-specific configuration information.

The application context is ApplicationContext -typed object.

(1) There are many classes implementing ApplicationContext. To use Java code with @Configuration — like our DaoFactory — use AnnotationConfigApplicationContext. The constructor takes DaoFactory.class.  

(2) Then, via the ApplicationContext object, getBean() lets you pull out a UserDao object. The parameter to getBean(), "userDao," is the name — the bean name (the name of a method declared in DaoFactory with @bean attached) 

> Get the bean named userDao  =  Call DaoFactory's userDao() and take the result

(3) Writing the code 


package springbook.user.dao;

import java.sql.SQLException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import springbook.user.domain.User;

	/**
	* 토비의 스피링 3.1 예제 따라하기 
	* 1장 - 05 스프링의 IoC - DaoFactory를 통해 설정 값에 접근하기
	* 
	* @since 	2019.02.22
	* @author 	친절한 찰쓰씨 http://normalstory.tistory.com
	*/
public class UserDaoTest {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {

		ApplicationContext context = 
				new AnnotationConfigApplicationContext(DaoFactory.class); // 추가된 코드 

		UserDao dao = context.getBean("userDao",UserDao.class);     // 변경된 코드 	

		User user = new User();
		
		user.setId("whiteship9");	   // <- PK에 해당하니까 수시로 변경 필요 
		user.setName("백기선");
		user.setPassword("married");
		
		dao.add(user);
		
		System.out.println(user.getId() + "등록 성공");
		
		User user2 = dao.get(user.getId());
		System.out.println(user2.getName());
		
		System.out.println(user2.getPassword());
		System.out.println(user2.getId()+"조회성공");
		
	}
}

3) Result: success ~

export_1.5.1 Spring IoC :  

study_spring190222_1.zip
Download


   1) Inside the project list on the left -> right-click empty space ->  
import -> Existing Projects into Workspace -> pick the downloaded file 

   2) If you imported the previous post's file, delete or rename the old project first, then re-import. 




1.5.2 How the application context works

1. How the example runs and the steps 

How the application context works and its process

2. Structural explanation

1) Clients don't need to know the concrete factory class.

When using the application context, even as object factories like DaoFactory multiply, clients don't need to know which factory to connect to. They can pull the desired object in a consistent way. And DaoFactory can carry IoC configuration in a simple form (like XML).

2) The application context provides full IoC services.

Their role isn't limited to creating objects and wiring relationships.

They let you tune how, when, and by what strategy objects are created, and on top of that provide features like auto-generation, post-processing of objects, info composition, varied configuration styles, interception, and more. They can also provide base-technology services beans can use or integration with external systems at the container level. 

3) The application context offers various ways to look up beans.

You can look up beans by type alone, or find beans that have specific annotations.


3. Glossary 

1) Bean or bean object 

managed object

An object managed by Spring via IoC. 

Not every object used in Spring.

Only objects that Spring directly creates and controls.


2) Bean Factory

The core container responsible for IoC. 

Creation and control of beans.

When written together as BeanFactory, it's the name of the most basic interface that a bean factory implements.


3) Application Context

Extends Bean Factory. 

Bean factory + Spring application support features. 

ApplicationContext when written together, it's the name of the basic interface application contexts must implement.


4) Configuration info / configuration metadata

configuration metadata — composition info or a blueprint. 

Used when creating and composing application objects managed by the IoC container. 


5) Container 

The word "container" itself embeds the IoC idea (it manages beans in an IoC fashion). An abstract term.

= (from the bean factory angle) = IoC container

= (from Spring's angle)application context = itself an object that implements the ApplicationContext interface.

And typically many of these objects are created and used within a single application. (Spring container ) 



This English version was translated by Claude.

zipJARs for tobe spring 1.5 spring IoC.zipzipstudy_spring190222_1.zip
친절한 찰쓰씨
Written by
친절한 찰쓰씨

Pleasant Charles — UI/UX researcher at AIT. Keeping notes on design, planning, and slow days here since 2010.

More on the author's page

Keep reading

Renewal

Steadily, for the long haul, without burning out

Mar 31, 2026·9 min
Renewal

Tech-life balance

Feb 7, 2026·3 min
Renewal

Humanality, by Park Jeong-ryeol

Feb 7, 2026·11 min