在idea的运行环境下,配置好Spring运行环境(通俗的理解配置环境就是在工程文件里面导入需要的jar包)
这里附上导入成功后的目录(网络上有很多很详细的导入过程,这里不在赘述)

1、创建Service接口和Service实现类
public interface UserService {
void add();
void add(User user); //方法的重载
}
public class UserServiceImpl implements UserService
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void add(User user) {
System.out.println("添加用户"+user);
}
public UserServiceImpl(){
System.out.println("UserServiceImpl()调用了");
}
@Override
public void add() {
System.out.println("创建用户。。。。" + name);
}
}
2、在beans.xml文件里面配置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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--配置一个bean-->
<!--spring内部创建对象的原理
1.解析xml文件,获取类名,id,属性
2.通过反射,用类型创建对象
3.给创建对象赋值
-->
<bean id = "userService" class = "com.service.UserServiceImpl">
<!--依赖注入数据,调用属性set方法 -->
<property name="name" value="zhangsan"> </property>
</bean>
</beans>
3、最后创建Lesson测试
public class Lesson {
@Test
public void test(){
//加载beans.xml这个spring配置文件,内部就会创建对象,ClassPath类路径加载:指的就是classes路径
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//从spring容器获取userService对象
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
4、测试通过

本文详细介绍了如何在IDEA中配置Spring运行环境,包括导入必要的库,创建Service接口与实现类,以及在beans.xml中配置Bean。通过一个具体的UserService示例,展示了如何进行依赖注入,并在Lesson测试类中成功调用方法,验证了配置的正确性。

被折叠的 条评论
为什么被折叠?



