认识:
- 注解就是一个类,例如:@Component
- 开发时,可用注解替代xml或并用
-
@component取代的是<bean class="">
-
web开发中,三个常见注解
- @Repository :dao层
- @Service:service层
- @Controller:web层
3.依赖注入,给私有字段设置,也可以给setter方法设置
普通值:@Value("")
引用值:
方式1:按照【类型】注入
@Autowired
方式2:按照【名称】注入1
@Autowired
@Qualifier("名称")
方式3:按照【名称】注入2
@Resource("名称")
实例类:
public class TestSetter {
@Test
public void demo1() {
String xmlPath = "f_setter_annotation/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
StudentAction studentAction = (StudentAction) applicationContext.getBean("studentActionId");
studentAction.execute();
}
}
其中studentActionId来自studentAction类(Web层)
@Controller("studentActionId")
public class StudentAction {
@Autowired
private StudentService studentService;
public void execute() {
studentService.addStudent();
}
}
studentService接口的实现类如下:(service层)
@Service
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
@Autowired
@Qualifier("studentDaoId")
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public void addStudent() {
studentDao.save();
}
}
studentDaoId来自studentDaoImpl类(dao层)
@Repository("studentDaoId")
public class StudentDaoImpl implements StudentDao {
@Override
public void save() {
System.out.println("dao");
}
}
spring配置(以下配置相同)
<?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/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">
<context:component-scan base-package="e_cycle"></context:component-scan>
</beans>
4.生命周期
初始化:@PostConstruct
销毁:@PreDestroy
@Controller("userServiceId")
public class UserServiceTmpl implements UserService{
@Override
public void addUser() {
System.out.println("d_scope add user");
}
@PostConstruct
public void myInit() {
System.out.println("初始化");
}
@PreDestroy
public void myDestroy() {
System.out.println("销毁");
}
}
5.作用域
@Scope("prototype") 多例
@Service("userServiceId")
@Scope("prototype")
public class UserServiceTmpl implements UserService{
@Override
public void addUser() {
System.out.println("d_scope add user");
}
}