Java框架spring Boot学习笔记:基于构造函数的依赖注入
Posted pyqb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java框架spring Boot学习笔记:基于构造函数的依赖注入相关的知识,希望对你有一定的参考价值。
编写User.java
1 package com.example.spring; 2 3 public class User { 4 private String name; 5 private Integer age; 6 private String country; 7 8 public User(String name, Integer age, String country) { 9 this.name = name; 10 this.age = age; 11 this.country = country; 12 } 13 14 public String toString() { 15 return name + " is " + age + " years old, living in " + country; 16 } 17 }
编写Beans.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="user" class="com.example.spring.User" > 7 <constructor-arg name="name" type="java.lang.String" value="Jacky" /> 8 <constructor-arg name="age" type="java.lang.Integer" value="22"/> 9 <constructor-arg name="country" type="java.lang.String" value="China"/> 10 </bean> 11 12 </beans>
编写Application.java
package com.example.spring; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application { public static void main(String[] args) { //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml //使用AbstractApplicationContext容器 AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml"); User user = (User)context.getBean("user"); System.out.println(user); } }
运行输出
Jacky is 22 years old, living in China
以上是关于Java框架spring Boot学习笔记:基于构造函数的依赖注入的主要内容,如果未能解决你的问题,请参考以下文章
Java框架spring Boot学习笔记:Spring相关概念
Java框架spring Boot学习笔记:注入对象类型属性
Java框架spring Boot学习笔记(十三):aop实例操作
Java框架spring Boot学习笔记:Bean的作用域