IOC:依赖注入
主要功能:让Spring生成对象
IOC配置主要分为两部分:
(1)让Spring能够生成对象
(2)使类通过Spring生成对象。
注解:
@Component:标注在实体类上
@Repository:标注在DAO上
@Service:标注在Service上
@Controller:标注在Controller上
配置过程:
(1)添加maven依赖
(2)添加Spring配置文件app.xml
(3)为那些想让Spring生成对象的类,添加相应的注解
(4)测试
具体过程:【本例中toString方法通过lombok注解获取】
(1)依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
(2)resources下添加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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<context:component-scan base-package="com.zparkep"/>
</beans>
注:
<context:component-scan base-package="XXX"/>需要根据包名修改。
(3)resources下添加app.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">
<import resource="spring.xml"/>
</beans>
(4)添加注解
@Service
public class UserService {
}
(5)测试
@Component
@ToString
public class User {
private Integer id;
private String username;
private String password;
private String tel;
}
public interface UserDao {
}
@Repository
public class UserDaoImpl implements UserDao {
}
public interface UserService {
}
@Service
public class UserServiceImpl implements UserService {
}
测试(传统方式)
@Test
public void fun3(){
//获取容器
ClassPathXmlApplicationContext act = new ClassPathXmlApplicationContext("app.xml");
//从容器中获取对象
UserDao user = (UserDao) act.getBean("userDaoImpl");
System.out.println(user);
}
结果
成功
注:getBean("")获取类的对象时,类名称的首字母小写。
例:User类映射为user,MyDemo类映射为myDemo。
补充
现在常使用Spring单元测试进行测试,配置过程如下:
(1)添加Maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
(2)测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:app.xml"})
public class SpringTest {
@Autowired
private UserService userServiceImpl;
@Test
public void fun(){
System.out.println(userServiceImpl);
}
}