spring中注入方式

参考:https://www.cnblogs.com/zhanyao/p/4409231.html

即 对于扫描到的类,Spring默认命名为首字母小写。
@Controller
public class LoginController{
}

等价于
<bean id="loginController" class="XXX.LoginController"/>

也可以自定义id的名字:

package com.test;

import org.springframework.stereotype.Component;

/**
 * 相当于<bean id="test"></bean>
 *
 */
@Component("test")
public class ExampleTest {
    public void show() {
        System.out.println("hello world");
    }
}

 

spring中注入方式,有属性set注入和构造函数注入

 

package com.spring.api;
 
public class Chinese implements Person {
    private Axe axe;
    public void setAxe(Axe axe) {
        this.axe = axe;
    }
    public void useAxe() {
        System.out.println("我打算去砍点柴火");
        System.out.println(axe.chop());
    }
}
package com.spring.api;
 
public class StoneAxe implements Axe { 
    public String chop() {
        return "石斧砍柴好慢";
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<?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="chinese" class="com.spring.api.Chinese">
        <property name="axe" ref="stoneAxe" />
    </bean>
    <bean id="stoneAxe" class="com.spring.api.StoneAxe" />
    <bean id="win" class="javax.swing.JFrame" />
    <bean id="date" class="java.util.Date" />
</beans>

 

 

属性注入:

 <bean id="English_level" class="com.myspring.second.EnglishLevel">

      <!-- set方法注入 -->

    <property name="course">

      <value>4级</value>

    </property>

  </bean>

<bean id="Math_level" class="com.myspring.second.MathCourse">

    <!-- 构造函数注入 -->

    <constructor-arg><value>1001</value></constructor-arg>

    <constructor-arg><value>离散数学</value></constructor-arg>

  </bean>

bean id="student" class="com.myspring.second.Student">

    <property name="eng">

      <ref bean="English_level"/>

    </property>

    <property name="mat">

      <ref bean="Math_level"/>

    </property>

  </bean>

-------------------------------------------------------------------------------------

property 的 name 属性值,在实体 bean 中必须有对应的 set 方法,否则会报错

<bean id="student" class="com.myspring.second.Student">

    <property name="eng">

      <ref bean="English_level"/>

    </property>

    <property name="mat">

      <ref bean="Math_level"/>

    </property>

  </bean>

对于这个bean,在 Student 类中必须存在:
setEng(String string){}
setMat(String string){}
这两个方法;
 
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值