Spring初学

一、依赖注入的类:两种方法 构造方法注入、setter注入

FIRST 

1.构造方法注入:首先写出基本要求

2.在资源文件中填入bean信息

 :<constructor-arg> 为属性 为构造器内属性赋值,可以不按照顺序赋值。

3.Test测试

import com.itheima.User1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUser1 {
    public static void main(String[] args) throws Exception {
//加载ApplicationContext.xml配置(资源文件信息获取)
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
//获取配置中User1实例 getBean()获取Spring容器中的bean信息
        User1 user1 = applicationContext.getBean("user1",User1.class);
        System.out.println(user1);
    }
}

4.result

 

 

 

SECOND

1.setter注入:

package com.itheima;

public class User2 {
    private int id;
    private String name;
    private int password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPassword() {
        return password;
    }

    public void setPassword(int password) {
        this.password = password;
    }

    public String toString(){
        return "id="+id+",name="+name+",password="+password;
    }
}

2.bean

 

 

<bean id="user2" class="com.itheima.User2">
        <property name="id" value="2"></property>
        <property name="name" value="bro"></property>
        <property name="password" value="467"></property>
    </bean>
//在bean中设置属性时,必须有set get方法,否则无法在property中设置。

3.Test

public class TestUser2 {
    public static void main(String[] args) throws Exception {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        User2 user2 = applicationContext.getBean("user2",User2.class);
        System.out.println(user2);
    }
}

4.Result

 

总结:

1.//加载ApplicationContext.xml配置(资源文件信息获取)时需要将资源文件名称填写完整:applicationtect.xml.

2.getBean方法的选择

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值