<?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-2.5.xsd">
<!--
把一个类放入到spring容器中,该类为bean
-->
<!--
id
唯一标识
把helloWorld放入到spring容器中了
-->
<bean id="helloWorld" class="com.oterman.create.HelloWorld1" ></bean>
<!-- 给helloWorld创建一个别名,注意name属性的值和bean的ID的值一致
-->
<alias name="helloWorld" alias= "俊哥好帅" />
</beans>
|
/**
* 测试创建对象
*/
@Test
public void
testCreate(){
/**
* 1.启动Spring容器
* 2.取出对象
* 3.调用方法
*/
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml" );
HelloWorld1 helloWorld=(HelloWorld1) context.getBean("helloWorld" );
helloWorld.hello();
}
/**
*测试别名
*/
@Test
public void
testAlias(){
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml" );
HelloWorld1 helloWorld1=(HelloWorld1 )
context.getBean("俊哥好帅" );
helloWorld1.hello();
}
|
public class HelloFactory
{
public static HelloWorld2
getInstance(){
//使用工厂可以控制调用哪一个构造方法
return new HelloWorld2();
}
}
|
<?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-2.5.xsd">
<bean id="helloWorld2" class="com.oterman.createmethod.HelloWorld2" ></bean >
<bean id="helloFactory" class="com.oterman.createmethod.HelloFactory" factory-method="getInstance" ></bean>
</beans>
|
< import resource ="com/oterman/createmethod/applicationContext_createMethod.xml" ></import>
|
/**
* 采用静态工厂模式创建对象
*/
@Test
public void
testCreate_Factory(){
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml" );
HelloWorld2 helloWorld2=(HelloWorld2) context.getBean("helloFactory" );
helloWorld2.hello();
}
|
windows-->preference--->myeclipse--->files and editors-->xml--->xmlcatalog 点击add ,在出现的窗口中的 Key Type 中选择URI,在location中选择File system,然后找到spring-beans-2.5.xsd文件所在地, 应该把窗口中的 Key Type改为Schema location , Key 改为http://www.springframework.org/schema/beans/spring-beans-2.5.xsd |
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/damogu_arthur/article/details/46939311