spring

bean实例化的三种配置,Spring的托管方式不同

  1. 新建一个Java项目,在项目中新建一个lib目录,往lib目录中导入以下几个架包在这里插入图片描述
    然后在lib目录上右键选择Build Path将其导入。
  2. 在src中新建一个test包,在包中新建一个C.java和test.java,在src中新建一个beans.xml文件,在beans.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"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 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:component-scan base-package="org.springframework.samples.petclinic.web"/>
 <!-- ... -->
</beans>
 - 1.beans实例化的第一种方式:调用构造方法
 - 配置这样写
 -    <bean id="c " class="test.C"/ >  
2.已经采用了工厂模式开发,但是不改动代码,如何配置bean

 - <bean id="factory" class="test.factory"></bean>
 - <bean id="E" factory-bean="factory" factory-method="getEInstance"></bean>

3.已经采用静态工厂模式开发,那么不改动代码如何配置bean
<bean id="k" class="test.StaticFactory" factory-method="getKInstance"/>

3.我们在beans.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"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 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">
 	<bean id="c" class="test.C"></bean>
</beans> 

4.进入我们新建的C.Java文件。我们在里面Source一个空的构造方法,在书写一个新的sayHello方法

public class C {

	public C() {
		System.out.println("C 被实例化了");
	}
	public void saHello() {
		System.out.println("Hello");
	}
}

5.进入test.Java文件中编写

package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test {

	public static void main(String[] args) {
		Resource resource = new ClassPathResource("beans.xml");
		
		BeanFactory factory = new XmlBeanFactory(resource);
		C c1 = (C) factory.getBean("c");
		System.out.println(c1);
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值