参考资料:https://how2j.cn/k/spring/spring-ioc-di/87.html、https://www.w3cschool.cn/wkspring/dgte1ica.htmlhtml
下载地址:https://how2j.cn/frontdownload?bean.id=1484spring
下载好后,把它们解压到项目的lib文件夹里面,若是没有该文件夹就新建一个。解压完后,用各自IDE的方法导入这些jar包app
代码注释以下:框架
public class Category { //属性 private String name; //设置该属性的方法 public void setName(String name){ this.name=name; } //获取该属性的方法 public void getName(){ System.out.println(name); } }
public class TestSpring { public static void main(String[] args) { //applicationContext.xml就是本身建立的配置文件 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //c就是后面配置文件的id Category category=(Category)context.getBean("c"); category.getName(); } }
摘自w3,须要注意到的两点:this
第一点是咱们使用框架 API ClassPathXmlApplicationContext() 来建立应用程序的上下文。这个 API 加载 beans 的配置文件并最终基于所提供的 API,它处理建立并初始化全部的对象,即在配置文件中提到的 beans。spa
配置文件后缀名为xml,须要本身新建。配置文件内容以下:code
<?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-3.0.xsd"> <!-- id本身命名,class就是须要注入属性的类--> <bean id="c" class="Category"> <!-- name就是属性的名称,value就是注入到该属性的值--> <property name="name" value="Hello Word"/> </bean> </beans>
最后运行结果就是咱们注入的xml
Hello Word