Spring快速入门

3.1、Bean标签的基本配置

用于配置对象交由Spring来创建

默认情况下它调用的是类中的无参构造函数,如果没有无参构造函数则不能创建成功。

基本属性:

  • id :Bean实例在Spring容器中的唯一标识。

  • class: Bean的全限定名称。

    <bean class="com.yl.dao.impl.StudentDaoImpl" id="studentDao" scope="prototype"></bean>

3.2、Bean标签的范围配置

scope:指对象的作用范围,取值如下,

 

在要注入属性的bean标签中进行配置,前提是该类有提供属性值对应的set方法。

    <bean class="com.yl.domain.Student" id="student" >
        <property name="name" value="王祖贤"></property>
        <property name="id" value="1"></property>
        <property name="age" value="24"></property>
    </bean>

public class Demo {
    public static void main(String[] args) {
//        创建IOC容器,传入配置文件名
//        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象,使用强制转换

//      通过bean属性来修改Student类中属性值
        Student student = (Student) app.getBean("student");
        System.out.println(student);
    }
}

 /*前提是student类中要有set方法否则就会报错
        NotWritablePropertyException: 
        Invalid property 'name' of bean class [com.yl.domain.Student]: 
        Bean property 'name' is not writable or has an invalid setter method. 
        Does the parameter type of the setter match the return type of the getter?
        */

如果类中有引用类型的变量

value表示变量的值

ref表示引用变量

<?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 class="com.yl.dao.impl.StudentDaoImpl" id="studentDao" scope="singleton"></bean>

    <bean class="com.yl.domain.Dog" id="dog" >
        <property name="color" value="白色"></property>
    </bean>
    <bean class="com.yl.domain.Student" id="student"  >
        <property name="name" value="王祖贤"></property>
        <property name="id" value="1"></property>
        <property name="age" value="24"></property>
<!--        如果Student中还有Dog(引用类型属性)就可以使用ref-->
        <property name="dog" ref="dog"></property>
    </bean>
    <bean class="com.yl.domain.Student" id="student2"  >
        <constructor-arg name="name" value="张三"></constructor-arg>
        <constructor-arg name="id" value="01"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="dog" ref="dog"></constructor-arg>
    </bean>

</beans>

二、Spring注解开发

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值