Spring容器

引言

         Spring容器是生成Bean实例的工厂,并管理容器中的Bean。

Spring容器

         Spring 容器最基本的接口就是BeanFactory。BeanFactory负责配置,创建、管理Bean,它有一个子接口:ApplictionContext,因此也被称为Spring上下文。Spring 容器还负责管理Bean与Bean 之间的依赖关系。

BeanFactory接口的基本方法

在这里插入图片描述

ApplictionContext

         Application Context 是BeanFactory 的子接口,因此功能更强大。对于大部分JavaEE应用而言,使用它作Spring容器更方便。其常用实现类FileSystemXmlApplicationContext ,ClassPathXrnlApplicationContext 和AnnotationConfigApplicationContext。如果在Web 应用中使用Spring 容器,则通常有XmlWebApplicationContext、AnnotationConfigWebApplicationContext 两个实现类。

使用ApplicationContext

创建Bean
public class Person
{
    public Person()
    {
        System.out.println("==正在执行Person无参数的构造器==");
    }
    public void setTest(String name)
    {
        System.out.println("正在调用setName()方法,传入参数为:" + name);
    }
}

配置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="chinese" class="Person" >
        <!-- 驱动Spring执行chinese Bean的setTest()方法,以"孙悟空"为传入参数 -->
        <property name="test" value="孙悟空"/>
    </bean>
</beans>
在测试类创建容器

        // 创建Spring容器
       ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
运行结果

在这里插入图片描述
怎么使用BeanFactory创建Spring容器呢

       // 搜索类加载路径下的beans.xml文件创建Resource对象
   ClassPathResource isr = new ClassPathResource("spring-config.xml");
	// 创建默认的BeanFactory容器
	DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
	// 让默认的BeanFactory容器加载默认的
    new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(isr);

运行结果
在这里插入图片描述
我们看到用BeanFactory并没有预初始化容器中的Bean.

         为了阻止Spring 容器预初始化容器中的singleton Bean 可以这样做<bean id="chinese" class="Person" lazy-init="true"/>该属性用于阻止容器预初始化该Bean

ApplicationContext的国际化支持

;

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
	<bean id="messageSource"
	class="org.springframework.context.support.ResourceBundleMessageSource">
		<!-- 驱动Spring调用messageSource Bean的setBasenames()方法,
			该方法需要一个数组参数,使用list元素配置多个数组元素 -->
		<property name="basenames">
			<list>
				<value>message</value>
				<!-- 如果有多个资源文件,全部列在此处 -->
			</list>
		</property>
	</bean>
</beans>

在这里插入图片描述

1
hello=欢迎你,{0}
now=现在时间是:{0}

2
hello=welcome,{0}
now=now is :{0}
3
hello=\u6b22\u8fce\u4f60\uff0c{0}
now=\u73b0\u5728\u65f6\u95f4\u662f\uff1a{0}
TestSpring
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.*;

public class SpringTest
{
	public static void main(String[] args)throws Exception
	{
		// 实例化ApplicationContext
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		// 使用getMessage()获取本地话信息
		// Locale的getDefault方法返回计算机环境的默认Locale
		String hello = ctx.getMessage("hello" , new String[]{"孙悟空"}
			, Locale.getDefault(Locale.Category.FORMAT));
		String now = ctx.getMessage("now" , new Object[]{new Date()}
			, Locale.getDefault(Locale.Category.FORMAT));
		// 打印两条信息
		System.out.println(hello);
		System.out.println(now);
	}
}

ApplicationContext的事件机制

在这里插入图片描述
在这里插入图片描述

实例

创建事件

import org.springframework.context.ApplicationEvent;
public class EmailEvent extends ApplicationEvent {
    private String address;
    private String text;

    public EmailEvent(Object source)
    {
        super(source);
    }
    // 初始化全部成员变量的构造器
    public EmailEvent(Object source , String address , String text)
    {
        super(source);
        this.address = address;
        this.text = text;
    }

    // address的setter和getter方法
    public void setAddress(String address)
    {
        this.address = address;
    }
    public String getAddress()
    {
        return this.address;
    }

    // text的setter和getter方法
    public void setText(String text)
    {
        this.text = text;
    }
    public String getText()
    {
        return this.text;
    }
}

创建监听器


import org.springframework.context.ApplicationListener;
import org.springframework.context.ApplicationEvent;


public class EmailNotifier implements ApplicationListener{
    // 该方法会在容器发生事件时自动触发
    @Override
    public void onApplicationEvent(ApplicationEvent evt) {

        // 只处理EmailEvent,模拟发送email通知...
        if (evt instanceof EmailEvent)
        {
            EmailEvent emailEvent = (EmailEvent)evt;
            System.out.println("需要发送邮件的接收地址  "
                    + emailEvent.getAddress());
            System.out.println("需要发送邮件的邮件正文  "
                    + emailEvent.getText());
        }
        else
        {
            // 其他事件不作任何处理
            System.out.println("其他事件:" + evt);
        }
    }
}

配置文件

<?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 class="EmailNotifier"/>
</beans>

测试类

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


public class SpringTest
{
    public static void main(String[] args)
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
        // 创建一个ApplicationEvent对象
        EmailEvent ele = new EmailEvent("test" ,
                "spring_test@163.com" , "this is a test");
        // 发布容器事件
        ctx.publishEvent(ele);
    }
}

运行结果
在这里插入图片描述

内置事件

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值