Spring的Bean详解=Bean别名+作用范围+使用场景
目录
Bean的别名:id和name的地位等同
Bean的作用范围:scope单例与非单例
Bean的使用场景:什么时候交给容器?什么时候不交?
Bean的别名实践(含代码)
如果看不懂下面的,例如不知道id写在哪里的,请首先看这篇博文:Spring的IoC、Bean、DI的简单实现,难度:※※※-CSDN博客
Bean的别名:id和name的地位等同
Bean的作用范围:scope单例与非单例
Bean的使用场景:什么时候交给容器?什么时候不交?
Bean的别名实践(含代码)
案例一:
案例二:
<?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="cat" class="org.example.package2.Cat"/>
<bean id="dog" class="org.example.package2.Dog"/>
<bean id="animalSet" name="abc1234" class="org.example.AnimalSet">
<property name="animal1" ref="cat"></property>
<property name="animal2" ref="cat"></property>
</bean>
</beans>
package org.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext iocContext = new ClassPathXmlApplicationContext("applicationConfig.xml");
AnimalSet animalSet = (AnimalSet) iocContext.getBean("abc1234");
System.out.println(animalSet);
animalSet.animalSetSound();
}
}
package org.example;
import org.example.package1.Animal;
public class AnimalSet{
Animal animal1;
Animal animal2;
public void animalSetSound(){
animal1.sound();
animal2.sound();
}
public void setAnimal1(Animal animal1) {
this.animal1 = animal1;
}
public void setAnimal2(Animal animal2) {
this.animal2 = animal2;
}
}
package org.example.package2;
import org.example.package1.Animal;
public class Cat implements Animal{
@Override
public void sound(){
System.out.println("cat sound");
}
}
package org.example.package2;
import org.example.package1.Animal;
public class Dog implements Animal {
public void sound() {
System.out.println("dog sound");
}
}
package org.example.package1;
public interface Animal {
void sound();
}