基于XML文件的方式配置Bean
IOC概念
IOC(Inversion of Control):其思想是反转资源获取的方向. 传统的资源查找方式要求组件向容器发起请求查找资源. 作为回应, 容器适时的返回资源. 而应用了 IOC 之后, 则是容器主动地将资源推送给它所管理的组件, 组件所要做的仅是选择一种合适的方式来接受资源. 这种行为也被称为查找的被动形式.
基于XML文件的方式配置Bean
1.首先创建java项目,导入关键的包,如下图所示 :

2.在根目录创建spring 配置文件,头部格式如下:
<?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" xmlns:p="http://www.springframework.org/schema/p" 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-4.0.xsd"> </beans>
3.创建一个实体类 (以常见的HelloWorld为例)
package com.atguigu.spring.helloworld; public class HelloWorld { private String user; public HelloWorld() { System.out.println("HelloWorld's constructor..."); } public void setUser(String user) { System.out.println("setUser:" + user); this.user = user; } public HelloWorld(String user) { this.user = user; } public void hello() { System.out.println("Hello: " + user); } }
4.xml配置bean方式
1)通过property标签
该方法需要有对应的setter方法,如HelloWorld上面的setUser方法
xml配置
<!-- 配置一个 bean -->
<bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld">
<!-- 为属性赋值 -->
<property name="user" value="Jerry"></property>
</bean>
main代码
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
helloWorld.hello();
2)通过constructor-arg标签
该方法是通过构造器来注入属性值
xml配置
<!-- 配置一个 bean -->
<bean id="helloWorld1" class="com.atguigu.spring.helloworld.HelloWorld">
<!-- 为属性赋值 -->
<constructor-arg value="cherry"></constructor-arg>
</bean>
main代码
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld1"); helloWorld.hello();
3)通过 p: 符
xml配置
<!-- 配置一个 bean -->
<bean id="helloWorld1" class="com.atguigu.spring.helloworld.HelloWorld" p:user="Jim"></bean>
main代码
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld2");
helloWorld.hello();

浙公网安备 33010602011771号