用bean来创建对象:
1.创建普通类,在这个类创建普通方法
public class User {
public void add() {
System.out.println("add......");
}
}
package com.atguigu.spring5;
public class User {
public void add(){
System.out.println("add...");
}
}
2.创建 Spring配置文件,在配置文件配置创建的对象
(
1)Spring 配置文件使用 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.xsd">
<
!--配置 User对象创建-->
<
bean id="user" class="com.atguigu.spring5.User"></bean>
<
/beans>
<?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.xsd">
<!-- 配置User对象创建-->
<bean id="user" class="com.atguigu.spring5.User"></bean>
</beans>
3.进行测试代码编写
package com.atguigu.spring5.testDemo;
import com.atguigu.spring5.User;
import javafx.application.Application;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring5 {
@Test
public void testAdd()
{
//1加载spring配置文件
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
//2获取配置创建的对象
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
}
Test
public void testAdd() {
/1 加载 spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
/2 获取配置创建的对象
/
/
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
运行截图: