spring中单例与多例:
1、Duck.java
2、Window.java
3、applicationContext-singleton.java
4、applicationContext.java
scope属性:指定单例与多例,常用的值有:singleton(单例)、prototype(多例)
alias标签:为某一个Bean取一个别名
name属性:与bean标签中的id值保持一致
alias属性:别名
1、Duck.java
package cn.java.singleton2;
public class Duck {
public Duck() {
System.out.println("Duck...无参构造方法");
}
}
2、Window.java
package cn.java.singleton2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Window {
public static void main(String[] args){
//1、启动spring框架
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.获取spring容器中某一创建好的对象
Duck duck1=(Duck) context.getBean("dk");
Duck duck2=(Duck) context.getBean("dk");
System.out.println(duck1);
System.out.println(duck2);
}
}
3、applicationContext-singleton.java
<?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">
<!--
scope属性:指定单例与多例,常用的值有:singleton(单例)、prototype(多例)
-->
<bean id="dk" class="cn.java.singleton2.Duck" scope="prototype"> </bean>
<!--
alias标签:为某一个Bean取一个别名
name属性:与bean标签中的id值保持一致
alias属性:别名
-->
<alias name="dk" alias="鸭子"/>
</beans>
4、applicationContext.java
<?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">
<!-- <import resource="cn/java/ioc1/applicationContext-ioc.xml"/> -->
<import resource="cn/java/singleton2/applicationContext-singleton.xml"/>
</beans>