加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML文件配置Bean

发布时间:2020-12-16 05:14:14 所属栏目:百科 来源:网络整理
导读:1、Spring配置文件都是由bean构成,配置一个基本的bean需要设置两个属性:id和class ?xml version="1.0" encoding="UTF-8"? !DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" beans bean id="hello"

1、Spring配置文件都是由<bean>构成,配置一个基本的bean需要设置两个属性:id和class

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="hello" class="test.hello">

</bean>

</beans>

hello是一个javaclass,id是它在BeanFactroy容器中的唯一标识。class是类的路径。

2、Spring如和创建和管理Bean

Spring对Bean的实例化分为单例模式和非单例模式。默认情况是单例模式。

<!--配置非单例模式-->

<bean id="hello" class="test.hello" singleton="false">

3、测试程序

package test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

//测试单例和非单例的区别

public class TestClient{

public static void main(String[] args){

ApplicationContext appContext = new FileSystemXmlApplicationContext("src/applicationContext.xml");

hello h1 = (hello)appContext.getBean("hello");

hello h12= (hello)appContext.getBean("hello");

if(h1==h2){

System.out.println("同一个Bean");

}else{

System.out.println("非同一个Bean");

}

}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读