所有和spring有关的包(有mybatis包的忽略),后期会使用maven引入
可命名为applicationContext-service.xml或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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="..."></bean>
</beans>
接口:UserService.java
public interface UserService {
//获取信息的方法
public void getMsg(String msg);
}
实现类:UserServiceImpl.java
public class UserServiceImpl implements UserService {
@Override
public void getMsg(String msg) {
System.out.println(msg);
}
}
public class Demo {
public static void main(String[] args) {
//获取spring配置文件生成的对象
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
//通过bean的id,获取bean对象
UserServiceImpl userService = (UserServiceImpl)ac.getBean("userService");
//使用方法
userService.getMsg("Hello,Spring!");
}
}
运行结果:
控制反转IOC:
public class Demo {
public static void main(String[] args) {
//获取spring配置文件生成的对象
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
//通过bean的id,获取bean对象
UserServiceImpl userService = (UserServiceImpl)ac.getBean("userService");
//比较连个对象的哈希值
System.out.println(userService.hashCode());
System.out.println("--------------------");
UserServiceImpl userService2 = (UserServiceImpl)ac.getBean("userService");
System.out.println(userService2.hashCode());
}
}
运行结果:
在配置文件中对应的<bean>标签中添加 scope=prototype 属性
<bean id="userService" class="com.yd.service.impl.UserServiceImpl" scope="prototype"></bean>
运行7.1中的代码结果:
原文:https://www.cnblogs.com/soft-test/p/14860858.html