Spring学习总结:二、Spring三种配置方式

三种配置方式

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值