1. 创建Bean
package cn.knightzz.xml.bean;
/**
* @author 王天赐
* @title: UserBean
* @projectName SpringIOC
* @description:
* @date 2021/10/9 21:40
*/
public class UserBean {
public void test() {
System.out.println("Hello Spring!");
}
}
2. 添加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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userBean" class="cn.knightzz.xml.bean.UserBean"></bean>
</beans>
3. 读取bean
package cn.knightzz.xml;
import cn.knightzz.xml.bean.UserBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
UserBean userBean = (UserBean) applicationContext.getBean("userBean");
userBean.test();
}
}
4. 增加多个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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
xmlns 即 xml namespace xml使用的命名空间
xmlns:xsi 即xml schema instance xml 遵守的具体规范
xsi:schemaLocation 本文档xml遵守的规范 官方指定
-->
<bean id="myBean" class="cn.knightzz.xml.bean.MyBean"></bean>
</beans>
package cn.knightzz.xml;
import cn.knightzz.xml.bean.MyBean;
import cn.knightzz.xml.bean.UserBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext2 =
new ClassPathXmlApplicationContext("spring.xml", "dao.xml");
MyBean myBean = (MyBean) applicationContext2.getBean("myBean");
UserBean userBean2 = (UserBean) applicationContext2.getBean("userBean");
myBean.test();
userBean2.test();
}
}