spring的管理都是以bean的形式:
格式:<bean class="类名" id="类名对应的唯一标识"></bean>
spring加载文件的两种方式:
//spring模式
//1.创建spring对象的工厂对象
// ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// //2.使用application.xml获取资源
// UserDao userDao = (UserDao) ctx.getBean("userDao");
// userDao.save();
//方式二这是从文件结构去找得到xml文件,不推荐使用
/*ApplicationContext ctx = new FileSystemXmlApplicationContext("");
//2.使用application.xml获取资源
UserDao userDao = (UserDao) ctx.getBean("userDao");
userDao.save();*/
配置applicationContext.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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!--spring管理资源都是bean的形式 -->
<!-- 你的资源是那个类的对象
<bean class="类名" id="类名对应的唯一标识"></bean>
-->
<bean class="com.array.ioc.base.UserDao" id="userDao"></bean>
<bean class="com.array.di.BookService" id="bservice">
<!--为BookService的属性设值取值 -->
<property name="name" value="array"></property>
<property name="age" value="20"></property>
</bean>
</beans>
为有属性的类注入值:
这里的name是属性名,value是属性值
<bean class="com.array.di.BookService" id="bservice">
<!--为BookService的属性设值取值 -->
<property name="name" value="array"></property>
<property name="age" value="20"></property>
</bean>
bean的java的类如下:
public class BookService {
// 提供一个私有变量
private String name;
// 提供私有变量的私有方法
private Integer age;
public BookService() {
System.out.println("bookservice构造函数");
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void save() {
// new BookDao().save();d
System.out.println("save " + name + age);
}
}
测试类如下:
public class DiApp {
//service依赖dio才能工作
public static void main(String[] args) {
//1.加载资源文件applicationContext.xml
ApplicationContext axt = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.注册的bean类
BookService bookService = (BookService) axt.getBean("bservice");
//3.调用bean类的sava方法
bookService.save();
}
}