前置知识:
@Component , @Repository , @ Controller , @Service 这些注解只局限于自己编写的类,而@Bean注解能把第三方库中的类实例加入IOC容器中并交给spring管理。
其中:
@Component一般用于公共类
@Repository 用于dao数据访问层
@Service 用于业务处理层
@ Controller 用于表示层
他们的用法基本的等价的,只是用于区分!!!
入门案例:
引入依赖:pom.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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="org.itheima"/>
</beans>
dao层:
public interface UserDAO {public void print();
}
@Repository
public class UserDAOImpl implements UserDAO {@Overridepublic void print() {System.out.println("userDAOImpl……");}
}
service层:
public interface UserService {public void write();
}
@Service
public class UserServiceImpl implements UserService {@Overridepublic void write() {System.out.println("UserService……");}
}
dao层测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring_config.xml")
public class UserDAOTest {@Resource
private UserDAO userDAO;@Testpublic void print() {userDAO.print();}
}
运行结果:
service测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring_config.xml")
public class UserServiceTest {@Resourceprivate UserService userService;@Testpublic void write() {userService.write();}
}
运行结果: