Spring/Study 2020. 4. 16. 21:16

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

프로젝트 전체 구조

1. java : 웹 애플리케이션에서 사용되는 Controller, Service, DAO 객체들의 java 파일의 위치

2. webapp : 스프링 설정파일, JSP, HTML 등 웹과 관련된 파일의 위치

3. resources : JSP 파일을 제외한 html, css, js 파일 등의 위치

4. spring : 스프링 설정파일의 위치

5. views : JSP 파일의 위치

6. xeb.xml : 웹 설정파일

7. pom.xml : Maven 설정 파일

 

web.xml

웹 애플리케이션에 최초 사용자의 요청이 발생하면 가장 먼저 DispatcherServlet이 사용자의 요청을 받는데, 개발자는 DispatcherServlet을 서블릿으로 등록해주어야 한다. 모든 사용자의 요청을 받기 위해 root를 의미하는 / 로 URL을 매핑한다.

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
cs

 

DispatcherServlet

- HandlerMapping : 적합한 Controller를 선택

- HandlerAdapter : 해당하는 Controller 내에서 가장 적합한 메소드를 선택

- ViewResolver : 가장 적합한 JSP 파일 선택

 

servlet-context.xml

웹 설정파일인 web.xml에 스프링 설정파일의 역할을 하는 파일로 지정되어있다. 클래스로부터 빈(Bean) 객체를 생성하고 조립하는 역할

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
cs

 

Controller

사용자의 요청을 실체로 처리하는 부분

@Controller
public class HomeController {
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        model.addAttribute("serverTime", formattedDate );
        
        return "home";
    }
}    
cs

 

View

클라이언트 요청정보(URL 매핑 값)에 해당하는 JSP파일 실행

posted by DevMoomin
:
Spring/Study 2020. 4. 15. 23:01

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

1. Eclipse 실행 후 Project Explorer 영역에서 마우스 우클릭 - New - Other... 클릭

2. spring을 검색해서 Spring Legacy Project 선택 후 Next 클릭

3. Project name을 입력하고, Spring MVC Project 선택 후 Next 클릭

4. Yes 클릭

5. package name 입력 후 Finish 클릭 (package name은 2단계 이상으로 해야 함)

6. 관련파일 다운로드 등이 완료될 때까지 대기(우측 하단에서 진행사항 확인)

7. 프로젝트 폴더 마우스 우클릭 - Run As - Run On Server를 클릭

8. Finish 클릭

9. 정상적으로 실행되는 것 확인

posted by DevMoomin
:
Spring/Study 2020. 4. 14. 11:28

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

Model1

JSP, Service, DAO를 하나의 파일로 처리하는 방식으로, 하나의 파일에서 모든 개발이 이루어지므로 개발 속도가 빠르지만 유지보수가 어렵다.

 

 

Model2

Controller, Service, DAO, View로 각각의 기능을 모듈화 하는 MVC 방식으로, 스프링에서 사용하는 방식이다. 특정 파일만 수정하면 되므로 유지보수가 수월하다.

 

 

스프링 MVC 프레임워크 설계구조

- HandlerMapping : 적합한 Controller를 선택

- HandlerAdapter : 해당하는 Controller 내에서 가장 적합한 메소드를 선택

- ViewResolver : 가장 적합한 JSP 파일 선택

 

DispatcherServlet 설정

JSP 웹 설정파일인 web.xml에 사용자의 모든 요청을 받기 위해 root를 의미하는 / 로 url을 매핑한다. 스프링 설정파일을 설정하면 스프링 컨테이너가 만들어지는데, 스프링 컨테이너에 HandlerMapping, HandlerAdapter, ViewResolver가 자동으로 생성되므로 개발자는 Controller와 View만 작업해주면 된다. (스프링 설정 파일을 설정하지 않으면 자동으로 설정해줌)

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
cs

 

Controller 객체 - @Controller

스프링 설정 파일에 <annotation-driven /> 태그를 넣어주면 스프링 컨테이너를 사용하기 위한 여러 기능을 하는 클래스들이 빈(Bean) 객체로 스프링 설정 파일에 존재하게 된다. 컨트롤러로 사용할 클래스 이름 앞에 @Controller 어노테이션을 명시해준다.

servlet-context.xml

<annotation-driven />
cs

HomeController.java

@Controller
public class HomeController {
 
}
cs

 

Controller 객체 - @RequestMapping

설정한 URL로 매핑이 되도록 한다.

@RequestMappint("/success")
public String success(Model model) {
 
    return "success";
}
cs

 

Controller 객체 - Model 타입의 파라미터

개발자는 Model 객체에 데이터를 담아서 DispatcherServlet에 전달할 수 있다. DispatcherServlet에 전달된 Model 데이터는 View에서 가공되어 클라이언트에게 응답처리된다.

model.setAttribute("tempData""model has data!!");
cs

 

@RequestMapping("/success")
public String success(Model model) {
 
    return "success";
}
cs

 

View 객체

스프링 설정 파일에 InternalResourceViewResolver라는 빈(Bean) 객체를 생성하는데, InternalResourceViewResolver는 prefix, 리턴 값, suffix 값을 합쳐서 적절한 View 파일로 매핑하는 역할을 한다.

/WEB-INF/views/success.jsp

@RequestMapping("/success")
public String success(Model model) {
 
    return "success";
}
cs

 

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

Colored by Color Scripter

cs

posted by DevMoomin
:
Spring/Study 2020. 4. 13. 17:10

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

하나의 설정 파일로 관리를 하다 보면 소스가 길어지면서 유지보수가 어려워질 수 있다. 따라서 설정 파일을 기능별로 분리해서 사용하는 것이 효율적이다.

 

배열 형식으로 넣어주는 방법

MainClass.java

public class MainClass {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = 
                new AnnotationConfigApplicationContext(MemberConfig1.class, MemberConfig2.class, MemberConfig3.class);
        
        EMSInformationService informationService = ctx.getBean("informationService", EMSInformationService.class);
        informationService.outputEMSInformation();
        
        ctx.close();    
    }
}
cs

 

@import 어노테이션을 사용하는 방법

MemberConfigImport.java

@Configuration
@Import({MemberConfig2.class, MemberConfig3.class})
public class MemberConfigImport {
    @Bean
    public StudentDao studentDao() {
        return new StudentDao();
    }    
}
cs

MainClass.java

public class MainClass {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = 
                new AnnotationConfigApplicationContext(MemberConfigImport.class);
        
        EMSInformationService informationService = ctx.getBean("informationService", EMSInformationService.class);
        informationService.outputEMSInformation();
 
        ctx.close();    
    }
}

Colored by Color Scripter

cs

posted by DevMoomin
:
Spring/Study 2020. 4. 13. 16:05

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

@Configuration 어노테이션은 JAVA 파일을 스프링 컨테이너로 사용하도록 명시해주는 어노테이션이다. 따라서 @Configuration 어노테이션을 통해 JAVA 파일이 스프링 컨테이너(xml) 역할을 하도록 할 수 있다. JAVA 파일에서는 @Bean 어노테이션을 사용하여 메소드로  빈(Bean) 객체를 생성한다.

 

bean

<?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 id="studentDao" class="ems.member.dao.StudentDao" ></bean>
 
</beans>
cs

 

@Configuration
public class MemberConfig {
    @Bean
    public StudentDao studentDao() {
        return new StudentDao();
    }
}
cs

 

constructor

<?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 id="registerService" class="ems.member.service.StudentRegisterService">
        <constructor-arg ref="studentDao" ></constructor-arg>
    </bean>
 
</beans>
cs

 

@Configuration
public class MemberConfig {
    @Bean
    public StudentRegisterService registerService() {
        return new StudentRegisterService(studentDao());
    }
}
cs

 

property

<?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 id="dataBaseConnectionInfoDev" class="ems.member.DataBaseConnectionInfo">
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
        <property name="userId" value="scott" />
        <property name="userPw" value="tiger" />
    </bean>
 
</beans>
cs

 

@Configuration
public class MemberConfig {
    @Bean    
    public DataBaseConnectionInfo dataBaseConnectionInfoDev() {
        DataBaseConnectionInfo infoDev = new DataBaseConnectionInfo();
        infoDev.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
        infoDev.setUserId("scott");
        infoDev.setUserPw("tiger");
        
        return infoDev;
    }
}
cs

 

list

<?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 id="informationService" class="ems.member.service.EMSInformationService">
        <property name="developers">
            <list>
                <value>Cheney.</value>
                <value>Eloy.</value>
                <value>Jasper.</value>
                <value>Dillon.</value>
                <value>Kian.</value>
            </list>
        </property>
    </bean>
 
</beans>
cs

 

@Configuration
public class MemberConfig {
    @Bean
    public EMSInformationService informationService() {
        EMSInformationService info = new EMSInformationService();
        
        ArrayList<String> developers = new ArrayList<String>();
        developers.add("Cheney.");
        developers.add("Eloy.");
        developers.add("Jasper.");
        developers.add("Dillon.");
        developers.add("Kian.");
        info.setDevelopers(developers);
        
        return info;
    }
}
cs

 

map

<?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 id="informationService" class="ems.member.service.EMSInformationService">
        <property name="administrators">
            <map>
                <entry>
                    <key>
                        <value>Cheney</value>
                    </key>
                    <value>cheney@springPjt.org</value>
                </entry>
                <entry>
                    <key>
                        <value>Jasper</value>
                    </key>
                    <value>jasper@springPjt.org</value>
                </entry>
            </map>
        </property>
    </bean>
 
</beans>
cs

 

@Configuration
public class MemberConfig {
    @Bean    
    public EMSInformationService informationService() {
        EMSInformationService info = new EMSInformationService();
        
        Map<StringString> administrators = new HashMap<StringString>();
        administrators.put("Cheney""cheney@springPjt.org");
        administrators.put("Jasper""jasper@springPjt.org");
        info.setAdministrators(administrators);
    
        return info;
    }
}

Colored by Color Scripter

cs

posted by DevMoomin
:
Spring/Study 2020. 4. 13. 15:25

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

스프링 컨테이너가 생성되면 컨테이터 내부에서 빈(Bean) 객체가 생성되고, 빈(Bean) 객체들은 서로 의존 관계를 가지고 있다. 따라서 스프링 컨테이너와 빈(Bean) 객체의 생명주기는 동일하다.

 

인터페이스(Interface)를 이용하는 방법

BookDao.java

public class BookDao implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("빈(Bean)객체 생성 단계");
    }
 
    @Override
    public void destroy() throws Exception {
        System.out.println("빈(Bean)객체 소멸 단계");
    }    
}
cs

 

init-method, destroy-method 속성을 이용하는 방법

appCtx.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:annotation-config />
 
    <bean id="bookRegisterService" class="com.brms.book.service.BookRegisterService" 
    init-method="initMethod" destroy-method="destroyMethod"/>
</beans>
cs

BookRegisterService.java

public class BookRegisterService {
    public void initMethod() {
        System.out.println("BookRegisterService 빈(Bean)객체 생성 단계");
    }
    
    public void destroyMethod() {
        System.out.println("BookRegisterService 빈(Bean)객체 소멸 단계");
    }
}

Colored by Color Scripter

cs

posted by DevMoomin
:
Spring/Study 2020. 4. 12. 20:02

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

@Qualifier

동일한 객체가 2개 이상인 경우, 스프링 컨테이너는 자동 주입 대상 객체를 판단하지 못해서 Exception을 발생시키는데, @Qualifier 어노테이션을 통해 주입할 객체를 명시함으로써 해결할 수 있다. (변수 이름과 Bean의 ID가 같은 경우 @Qualifier 어노테이션이 없어도 에러가 발생하지 않지만 추천하는 방식은 아니다.)

appCtx.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:annotation-config />
 
    <bean id="wordDao" class="com.word.dao.WordDao" >
        <qualifier value="usedDao"/>
    </bean>
    <bean id="wordDao2" class="com.word.dao.WordDao" />
    <bean id="wordDao3" class="com.word.dao.WordDao" />
</beans>
cs

WordRegisterService.java

@Autowired
@Qualifier("usedDao")
private WordDao wordDao;
cs

 

의존객체 자동 주입 체크

자동 주입할 객체가 없는 경우 Exception이 발생하는데, required=false 속성을 통해 자동 주입할 객체가 없는 경우에는 주입하지 않도록 함으로써 Exception을 방지할 수 있다.

WordRegisterService.java

@Autowired(required=false)
private WordDao wordDao;
cs

 

@Inject

@Autowired처럼 의존객체를 자동으로 주입을 할 수 있지만, required 속성을 지원하지 않는다. @Qualifier 대신 @Named 어노테이션을 사용한다. (@Inject 보다 @Autowired를 더 많이 사용)

appCtx.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:annotation-config />
    
    <bean id="wordDao1" class="com.word.dao.WordDao" />
    <bean id="wordDao2" class="com.word.dao.WordDao" />
</beans>
cs

WordRegisterService.java

@Inject
@Named(value="wordDao1")
private WordDao wordDao;

cs

posted by DevMoomin
:
Spring/Study 2020. 4. 10. 18:28

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

의존객체 자동 주입이란 스프링 설정파일에서 의존객체를 주입할 때 <constructor-arg> 또는 <property> 태그로 대상객체를 명시하지 않아도 스프링 컨테이너가 자동으로 필요한 의존대상 객체를 찾아서 주입해 주는 기능을 말한다.

 

@Autowired

주입하려고 하는 객체의 타입이 일치하는 객체를 자동으로 주입 (생성자, 변수, 메소드에 사용가능)

변수나 메소드에서 사용할 때는 객체가 생성되어야 주입이 가능하므로 Default 생성자 필요

WordRegisterService.java

@Autowired
public WordRegisterServiceUseAutowired(WordDao wordDao) {
    this.wordDao = wordDao;
}
cs

appCtx.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:annotation-config />
 
    <bean id="wordDao" class="com.word.dao.WordDao" />    
</beans>
cs

 

@Resource

주입하려고 하는 객체의 이름이 일치하는 객체를 자동으로 주입 (변수, 메소드에 사용가능)

변수나 메소드에서 사용할 때는 객체가 생성되어야 주입이 가능하므로 Default 생성자 필요

WordRegisterService.java

@Resource
private WordDao wordDao;
    
public WordRegisterServiceUseResource() {
    
}
    
//@Resource
public WordRegisterServiceUseResource(WordDao wordDao) {
    this.wordDao = wordDao;
}
cs

appCtx.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:annotation-config />
 
    <bean id="wordDao" class="com.word.dao.WordDao" />
        
</beans>

Colored by Color Scripter

cs

 

posted by DevMoomin
:
Spring/Study 2020. 4. 9. 16:27

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

싱글톤(Singleton)

스프링 컨테이너에서 생성된 빈(Bean) 객체의 경우 동일한 타입에 대해서는 기본적으로 한 개만 생성이 되며, getBean() 메소드로 호출될 때 동일한 객체가 반환된다. scope 속성을 명시하지 않으면 기본적으로 싱글톤으로 설정된다.

DependencyBean.java

package scope.ex;
 
public class DependencyBean {
    public DependencyBean() {
        System.out.println("DependencyBean : constructor");
    }
}
cs

applicationContext.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 id="dependencyBean" class="scope.ex.DependencyBean" />
    
</beans>
cs

MainClass.java

package scope.ex;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
        
        DependencyBean dependencyBean1 = ctx.getBean("dependencyBean", DependencyBean.class);
        DependencyBean dependencyBean2 = ctx.getBean("dependencyBean", DependencyBean.class);
        
        if(dependencyBean1.equals(dependencyBean2)) System.out.println("dependencyBean1 == dependencyBean2");
        else System.out.println("dependencyBean1 != dependencyBean2");
        
        ctx.close();
    }
}
cs

실행결과

 

프로토타입(Prototype)

new로 객체를 생성할 때와 마찬가지로 getBean() 메소드로 호출할 때마다 매번 새로운 객체를 만든다. scope속성에서 protype이라고 명시를 해주어야 한다.

DependencyBean.java

package scope.ex;
 
public class DependencyBean {
    public DependencyBean() {
        System.out.println("DependencyBean : constructor");
    }
}
cs

applicationContext.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 id="dependencyBean" class="scope.ex.DependencyBean" scope="prototype" />
    
</beans>
cs

MainClass.java

package scope.ex;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
        
        DependencyBean dependencyBean1 = ctx.getBean("dependencyBean", DependencyBean.class);
        DependencyBean dependencyBean2 = ctx.getBean("dependencyBean", DependencyBean.class);
        
        if(dependencyBean1.equals(dependencyBean2)) System.out.println("dependencyBean1 == dependencyBean2");
        else System.out.println("dependencyBean1 != dependencyBean2");
        
        ctx.close();
    }
}
cs

실행결과

posted by DevMoomin
:
Spring/Study 2020. 4. 9. 15:26

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

하나의 XML 파일에 너무 많은 내용이 들어있으면 가독성 등에서 문제가 발생하게 되는데, 기능별로 구분해서 XML 파일을 나누어주어 이러한 문제를 해결할 수 있다.

분리한 스프링 설정 파일은 배열을 이용하여 한번에 가져와서 사용할 수도 있고, 하나의 설정 파일에 여러 설정 파일을 import 해놓고, 해당 설정 파일만을 가져와서 사용할 수도 있다.

 

 

배열로 사용하는 방법

MainClass.java

String[] appCtxs = {"classpath:appCtx1.xml""classpath:appCtx2.xml""classpath:appCtx3.xml"};
 
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(appCtxs);
cs

 

import로 사용하는 방법

applicationContext.xml

<import resource="classpath:appCtx1.xml" />
<import resource="classpath:appCtx2.xml" />
<import resource="classpath:appCtx3.xml" />
cs

MainClass.java

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");

cs

posted by DevMoomin
: