依赖注入2(构造函数实例化bean)

本文介绍了一个使用Spring框架进行依赖注入的例子,包括JavaBean的定义、XML配置及测试类的实现。通过构造函数注入的方式,展示了如何创建并管理对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.javabean

package com.bean;

public class Hello {

 private String hello;

 public Hello(String name) {

  hello=name;
 }
 public String getHello() {
  return hello;
 }
 public void setHello(String hello) {
  this.hello = hello;
 }
 public void show() {
  System.out.println("hello:"+hello);
 }
}

 

2.配置文件

<?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-4.3.xsd">
  
  <!-- bean就是javabean对象,由spring来创建和管理 ,其实是使用无参构造方法创建对象-->
  <!-- singleton表示创建的java对象是单例模式,默认的模式,只存在一个bean,
  prototype表示创建的对象是原型模式,即每调用一次getBean就生成一个Bean的实例-->
  <!-- 构造函数注入 注意:name指的是构造函数参数的名字 -->
  <bean id="Hello" class="com.bean.Hello">
   <!-- 根据参数的名字 当构造函数中含有其他bean的对象时,将value换成ref后,值换成类的id-->
   <constructor-arg name="name" value="hello"/>
   
   <!-- 根据参数索引 -->
   <!-- <constructor-arg index="0" value="hello"/> -->
   
   <!-- 根据类型匹配 -->
   <!-- <constructor-arg type="String" value="hello"/> -->
  </bean>
</beans>

3.测试类


 

package com.Test;

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

import com.bean.Hello;

public class Test1 {

 //控制反转
 //控制:指谁来控制对象的创建,spring来创建对象
 //反转:程序本身不创建对象,而是变成被动的接受spring创建好的对象
 //正转:在程序中主动创建对象
 public static void  main(String[] arges) {
  ApplicationContext context=new ClassPathXmlApplicationContext("config.xml");
  Hello hello=(Hello) context.getBean("Hello");
  hello.show();
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值