三种配置方式
1. 基于Xml配置文件
2. 基于注解
3. 基于java代码
一、基于XML配置文件
1. 基于构造方法
(1)、 基于无参构造方法(默认)
<bean id="marysa" class="com.softeem.entity.Woman" />
public Woman() {
System.out.println("午餐方法....");
}
public Woman(String name, int age, String outlook) {
System.out.println("有方法....");
this.name = name;
this.age = age;
this.outlook = outlook;
}
/**
* Spring
*/
public class SpringClass2Application {
public static void main(String[] args) {
//ClassPathXmlApplicationContext通过配置文件的类路径实例化容器
ApplicationContext applicationContext =
new
ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Woman marysa = (Woman)applicationContext.getBean("marysa");
System.out.println(marysa);
}
}
(2)、 基于有参构造方法
//根据有参构造方法参数的属性名
<bean id="coco" class="com.softeem.entity.Woman">
<constructor-arg name="name" value="可可" />
<constructor-arg name="age" value="20" />
2. 基于工厂(隐藏类的创建过程)
1. 工厂实例
<constructor-arg name="outlook" value="长发的" />
</bean>
//使用index 下标
<bean id="huahua" class="com.softeem.entity.Woman">
<constructor-arg index="0" value="小王" />
<constructor-arg index="1" value="20" />
<constructor-arg index="2" value="182" />
</bean>
//还有基于有参构造方法参数的类型(type)的
public class SpringClass2Application {
public static void main(String[] args) {
//ClassPathXmlApplicationContext通过配置文件的类路径实例化容器
ApplicationContext applicationContext =
new
ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Woman marysa = (Woman)applicationContext.getBean("marysa");
System.out.println(marysa);
Woman coco = (Woman)applicationContext.getBean("coco");
System.out.println(coco);
Woman huahua = (Woman)applicationContext.getBean("huahua");
System.out.println(huahua);
}
}
二、 基于工厂(隐藏类的创建过程)
1. 工厂实例
/**
* 工厂实例对象通过实例方法创建Bean
*/
public class WomanFactory {
public Woman selectLili(){
System.out.println("开始创建了");
Woman lili = new Woman();
lili.setName("小红");
lili.setAge(7);
lili.setOutlook("长发的");
System.out.println("创建完毕");
return lili;
}
public Woman selectMary(){
Woman mary = new Woman();
mary.setName("玛丽");
mary.setAge(9);
mary.setOutlook("短发的的");
return mary;
}
public WomanFactory() {
System.out.println("实例工厂开始进行中....");
}
}
<!-- 利用工厂实例方法去获取对象 -->
<bean id="womanFactory" class="com.softeem.factory.WomanFactory" />
<bean id="lili" factory-bean="womanFactory" factory-method="selectLili"
/>
<bean id="mary" factory-bean="womanFactory" factory-method="selectMary"
/>
2. 静态工厂
/**
* 静态工厂
* @author [email protected]
* @since 2021年3月27