参考资料:https://how2j.cn/k/spring/spring-ioc-di/87.html、https://www.w3cschool.cn/wkspring/dgte1ica.html
下载地址:https://how2j.cn/frontdownload?bean.id=1484
下载好后,把它们解压到项目的lib文件夹里面,如果没有该文件夹就新建一个。解压完后,用各自IDE的方法导入这些jar包
代码注释如下:
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,需要注意到的两点:
第一点是我们使用框架 API ClassPathXmlApplicationContext() 来创建应用程序的上下文。这个 API 加载 beans 的配置文件并最终基于所提供的 API,它处理创建并初始化所有的对象,即在配置文件中提到的 beans。
配置文件后缀名为xml,需要自己新建。配置文件内容如下:
<?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>
最后运行结果就是我们注入的
Hello Word
原文:https://www.cnblogs.com/lbhym/p/11892428.html