Spring入门-配置文件方式

一、基础配置

1、导入Spring依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

2、写一个简单的实体类Person,包含name和age两个字段,并提供set/get方法和构造方法。

3、 编写Spring的配置文件SpringConfig.xml

<?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">
    
</beans>

二、Bean的注入

        1、通过set方法注入bean,需要在配置文件中配置bean。其中bean标签中 id代表bean的id,class是要注入实体的实体类,property表示注入的属性。需要注意的是,要在Person类中提供set方法才可以注入成功。

<?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="Dao" class="com.fbd.pojo.Person">
        <property name="name" value="张三"></property>
        <property name="age" value="10"></property>
    </bean>
</beans>

         2、通过构造方法注入,使用此方式注入bean需要在Person类中提供构造方法。如果按照构造方法参数的顺序注入,可以不用写index。

<bean id="Dao" class="com.fbd.pojo.Person">
    <constructor-arg  index="0" value="李四"/>
    <constructor-arg  index="1" value="12"/>
</bean>

三、获取bean

public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("SpringConfig.xml");
        Object dao = context.getBean("Dao");
        System.out.println(dao);
}

  编写一个测试类,创建ClassPathXmlApplicationContext对象,通过getBean方法获取bean,

getBean()方法中可以传入bean的id,即通过bean的名称获取bean,也可以通过bean的类型获取bean,例如:

Person bean = context.getBean(Person.class);

要注意,通过类型注入,不能写两个同类型的bean,否则会报异常。比如:

    <bean id="Dao1" class="com.fbd.pojo.Person">
        <constructor-arg type="java.lang.String" index="0" value="李四"/>
        <constructor-arg  type="int" index="1" value="12"/>
    </bean>
    <bean id="Dao2" class="com.fbd.pojo.Person">
        <property name="age" value="12"></property>
        <property name="name" value="张三"></property>
    </bean>

上面在配置文件中写了两个bean,都是Person类的,尝试通过类型获取bean。抛出以下异常:

  可以使用bean名称获取bean,解决这类的异常。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值