一、环境准备
Spring配置文件 applicationContext.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/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 开启自动扫描 -->
<context:component-scan base-package="待扫描的包"/>
</beans>
二、相关注解
- @Repository:标记数据访问层(dao)
- @Controller:标记控制器层(controller)
- @Service:标记业务层(service)
- @Component:标记通用组件
要点
- 如果使用默认注解,则类对应的bean的id为开头字母小写的类名
- 如果想要自定义bean的id,则对注解的value属性赋值即可
//无参 bean id为student
@Controller()
public class Student {
private String name;
private String id;
}
//bean id为 s1
//@Controller("s1")
@Controller(value = "s1")
public class Student {
private String name;
private String id;
}
- 在类上使用以上四个注解后,Spring会自动创建相应的BeanDefinition对象,并注册到ApplicationContext中
- 可以创建自定义注解,然后在注解上标注@Component,该自定义注解就具有了@Component的功能
- 以上4个注解功能相同,只是作用位置不同,增强可读性