一、前提
在配置文件中设置bean扫描的根路径
<?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:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--设置需要存储到spring中的bean根目录-->
<content:component-scan base-package="com.beans"></content:component-scan>
</beans>
1.通过注解将bean存储到Spring中,这样的注解有类注解和方法注解两种
a.类注解
①@Controller (控制器)
②@Service (服务)
③@Repository (仓库)
④@Component (组件)
⑤@Configuration (配置)
b.方法注解
@Bean的使用:将当前返回的方法存储到spring中
①使用前提是当前类同样需要加五大类的标签
②bean的重命名(一个或者多个):
@Bean(name="rename")
@Bean({"reanmea","renameb"})
一般的,Bean会有一个默认的命名,在重命名之后,新的命名会覆盖掉默认命名。
2.一些注意事项:
(1)我们添加了bean扫描路径之后,仍需要添加类注解
(2) 添加了注解的类,必须放到扫描路径下才能被扫描到。
(3)类注解的bean的命名规则:
①第一个字母大写,第二个字母小写,小驼峰规则,将类名小写。
②第一个和第二个字母都大写,命名就是类名。
(4)类注解之间的关系:Component是其他注解的父类。
3.获取对象的注解@Autowired的三种方法:
①属性注入
@Autowired
private UserService userService;
②构造方法注入
private UserService userService;
@Autowired
public UserController(UserService uservicec){
this.uservice = uservice;
}
③set方法注入
private UserService userService;
@Autowired
public void setUserController(UserService uservicec){
this.uservice = uservice;
}
面试题:属性注入、构造方法注入、set方法注入之间的区别是什么?
--属性注入的写法最简单,缺点是不通用,只适用于Ioc框架。
--setter注入:是Spring早期版本推荐的注入方式,通用性不如构造方法注入。
--构造方法注入:优点是通用性好,保证在调用对象之前,这个对象是一点过存在的。
缺点是可能存在传递多个构造方法的初始化,会导致代码臃肿。