基本说明
spring的第一个例子,说明如何通过配置文件生成对象的实例
创建工程
工程目录结构
导入jar包
spring的jar包可以从以下链接去找:
https://how2j.cn/k/spring/spring-ioc-di/87.html
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com"/>
</beans>
注:
<context:component-scan base-package="com"/>,需要对com包进行扫描
Bean类
@component("h"),告诉spring是一个组件
package com;
import org.springframework.stereotype.Component;
@Component("h")
public class Hero {
private String name ="ljy";
private int hp = 100;
private int mp = 100;
Hero() {
this.name = "twj";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}
}
测试类
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
Hero h = (Hero) context.getBean("h");
System.out.println("hero:" + h.getName());
}
}
结果
jy_lu 发布了2 篇原创文章 · 获赞 0 · 访问量 45 私信 关注