Spring_01 Bean的注入方式

Bean注入的三种方式:

(1)接口注入(不推荐)

(2)Setter注入 

(3)构造器注入

Spring不去对接口注入作支持,因为通过接口注入总归是要 给对象进行赋值的,是存在耦合的,这违背了spring的初衷

<?xml version="1.0" encoding="UTF-8"?>  
<!-- xmlns 命名空间,类似于包名 
	 xml   遵循的标签规范
-->
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:context="http://www.springframework.org/schema/context" 
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context.xsd 
       ">
    <!-- setter注入 -->   
    <bean id="student_zhangsan" class="com.app.model.Student">  
        <property name="name" value="zhangsan" />
        <property name="age"  value="11" />  
        <property name="sex"  value="male" />  
    </bean>   
    <!-- 构造注入  -->
    <bean id="student_lisi" class="com.app.model.Student">
    	<constructor-arg name="name" value="lisi"></constructor-arg>
    	<constructor-arg name="age"  value="13"></constructor-arg>
    	<constructor-arg name="sex"  value="female"></constructor-arg>
    </bean>                     
</beans>  
package com.app.pre;

import javax.annotation.PostConstruct;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.app.model.Student;

@Component
public class Preload {

    @PostConstruct
    private void init() {
        
        @SuppressWarnings("resource")
        //spring 容器
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
        
        //容器管理整所有的bean,BeanFactory提供ApplicationContext获取bean实例的接口
         
        //spring set注入创建对象时调用的是默认构造方法,若显示进行声明构造器,必须存在默认构造方法
        Student student1  = (Student) context.getBean("student_zhangsan");
        
        Student student2  = (Student) context.getBean("student_zhangsan");
        
        //单例bean
        System.out.print(context.isSingleton("student_zhangsan")+"\r\n");
        
        System.out.print(student1.getName()+"\r\n");
        
        //两者对象的hashcode相等,且是单例bean,说明spring容器创建的这个对象是单例类
        System.out.print(student1.hashCode()+"\r\n");
        
        System.out.print(student2.hashCode()+"\r\n");
        
        Student student3 = (Student) context.getBean("student_lisi");
        
        System.out.print(student3.getName()+"\r\n");        
        
        System.out.print(student3.getSex()+"\r\n");        
    }
}

 

true
zhangsan
1979080261
1979080261
lisi
female

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值