启动注解功能
- 启动注解扫描,加载类中配置的注解项
<context:component-scan base-package="packageName"/>
- 说明:
- 在进行包所扫描时,会对配置的包及其子包中所有文件进行扫描
- 扫描过程中以文件夹递归迭代的形式进行的
- 扫描过程仅读取合法的java文件
- 扫描时仅读取spring可识别的注解
- 扫描结束后会将可识别的有效注解转化为spring对应的资源加入IoC容器
- 注意:
- 无论是注解格式还是XML配置格式,最终都是将资源加载到IoC容器中,差别仅仅是数据读取方式不同
- 从加载效率上来说注解优于XML配置文件
新建一个项目
pom.xml内容
在resources文件里新建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/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
</beans>
固定注解和内容如上
其他文件和内容如下图所示
App内容
bean的定义
- 名称:@Component、@Controller、@Service、@Repository
- 类型:类注解
- 位置:类定义上方
- 作用:设置该类为spring管理的bean
- 范例:
@Component
public class ClassName()
- 说明
- @Controller、@Service、@Repository是@Component的衍生注解,功能同@Component
- 相关属性:
- valueI(默认):定义bean的访问id
首先运行测试程序,正常运行
修改applicationContext.xml
在UserServiceImpl里添加@Component(“userService”)
运行可见正常
同理注解掉另外两个,添加两个@Component
运行结果:
正常运行
bean的作用域
- 名称:@Scope
- 类型:类注解
- 位置:类定义上方
- 作用:设置该类作为bean对应的scope属性
- 范例:
@Scope
public class ClassName{}
- 相关属性
- value(默认):定义bean的作用域,默认为singleton
修改UserServiceImpl的内容
运行结果:
- 开启注解驱动
- bean的四种注解定义格式
- bean的相关属性注解格式
- id
- class
- scope
- init-method
- destroy-method