【Spring】初始化Spring IoC容器(非Web应用),并获取Bean

参考文章

Introduction to the Spring IoC container and beans

BeanFactory 和ApplicationContext(Bean工厂和应用上下文)

Spring ApplicationContext - Resource leak: 'context' is never closed

版本说明

  • JDK 1.7
  • Spring3.2.14
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.14.RELEASE</version>
</dependency>

Java项目中,启动Spring IoC、获取Bean

CLASS PATH下放一个最简单的Spring配置文件

<?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-3.0.xsd"> <bean id="demoBean" class="com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean">
</bean> </beans>

需要由Spring托管的Bean Class

package com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean;

public class DemoBean {

    public String test() {
return "hello spring...";
} }

调用类

package com.nicchagil.springapplication.No001initSpringIocAndGetABean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean; public class Call { public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
DemoBean d1 = context.getBean("demoBean", DemoBean.class);
DemoBean d2 = context.getBean("demoBean", DemoBean.class); /* execu the method*/
System.out.println(d1.test());
System.out.println(d2.test()); /* default singleton */
System.out.println("demoBean isSingleton ? -> " + context.isSingleton("demoBean"));
System.out.println(d1);
System.out.println(d2);
System.out.println("d1 == d2 -> " + (d1 == d2));
} }

日志

hello spring...
hello spring...
demoBean isSingleton ? -> true
com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean@4857b188
com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean@4857b188
d1 == d2 -> true
上一篇:HDU_5523Game


下一篇:[Luogu4631][APIO2018] Circle selection 选圆圈