文章目录
自动扫描:
使用注解步骤
1.在配置文件中,开启自动扫描,component-scan,并指定扫描的包。
<?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">
<!-- 开启扫描 扫描pojo包-->
<context:component-scan base-package="mybatisdemo.pojo"/>
</beans>
2.需要在要加入到IOC容器中的类上面加上注解
- @Component @Controller @Service @Repository
- 创建容器的时候,扫描指定包下面的,带有以上注解的类。
3.扫描到IOC容器中的bean,id默认为非限定类名,首字母小写。列如:Role–role
4.关于id,还可以使用注解的value属性来指定器id。例如@Component(“role”)
面试问题:@Component @Controller @Service @Repository的区别?
功能相同,其他3个都是基于@Component实现的;不同的是只是为了在不同的层使用作为区分使用的
@Autowired 自动装配 或者 @Resource(不是spring的注解)
-
1.在IOC中进行byType根据类型进行查找,
-
2.有多个相同类型的bean,那么会采用byName的方式进行匹配。(注:根据属性名进行查找)
-
@Autowired private SysRole role1;
-
3.如果在IOC容器中找不到匹配的bean,那么默认会抛异常。可以使用@Autowried(required=“false”)
- 可以使用@Resource自动装配指定名的bean;列如
@Resource(name = "roele2")
private SysRole role;