实现IOC的准备工作
编写空的配置文件,如需要配置文件支持注解开发,需要添加新的约束。
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
添加完之后约束如下
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
</beans>
@Component
作用:用于创建对象,放入Spring容器,相当于<bean id="" class="">
位置:类上方。
- 还需要在配置文件中配置扫描的包,扫描到该注解才能生效
<context:component-scan base-package="包名"></context:component-scan> - @Component 注解配置bean的默认id是首字母小写的类名。也可以手动设置bean的id值。
@Repository @Service @Controller
作用:这三个注解的作用和@Conponent的作用一样,使用它们是为了区分该类属于哪一个层
- @Repository用于Dao层
- @Service用于Service层
- @Controller用于Controller层
@Scope
作用:指定bean的创建策略
位置:类上方
取值:singleton prototype request session globalsession
@Autowired
作用:从容器中查找符合属性类型的对象自动注入属性中。用于代替<bean>中的依赖注入配置。
位置:属性上方、setter方法上方、构造方法上方。
注意:
- @Autowired 写在属性上方进行依赖注入时,可以省略setter方法。
- 容器中没有对应类型的对象会报错
- 容器中有多个对象匹配类型时,会找beanId等于属性名的对象,找不到会报错。
@Qualifier
作用:按照类型注入对象的基础上再按照bean的id注入
位置:属性上方
注意:@Qualifier必须和@Autowired一起使用
@Value
作用:注入String类型和基本数据类型的属性值
位置:属性上方
-
直接设置固定的属性值
在属性上方直接加入该注解并且赋值
-
获取配置文件中的属性值
1.编写配置文件db.properties
jdbc.username=root
jdbc.password=123456
- spring核心配置文件扫描配置文件
<context:property-placeholder location="db.properties">
</context:property-placeholder>
- 编写配置文件中的属性值
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Configuration
作用:脱离配置文件,使用纯注解实现开发。但是在真实开发中我们还是会保留配置文件,因为使用配置文件会更方便
纯注解实现IOC需要一个Java类代替xml文件。这个Java类上方需要添加@Configuration,表示该类是一个配置类,作用是代替配置文件。
@ComponentScan
作用:指定spring在初始化容器时所扫描的包
位置:配置类上方括号中添加包名
@PropertySource
作用:代替配置文件中的 <context:property-placeholder> 扫描配置文件
位置:配置类上方
注意:配置文件前要加关键字classpsth
例如:@PropertySource("classpath:db.properties")
@Bean
- 作用:将方法的返回值对象放入Spring容器中。如果想将第三方类的对象放入容器,可以使用@Bean
- 位置:配置类的方法上方。
- 属性:name:给bean对象设置id
- 注意:@Bean修饰的方法如果有参数,spring会根据参数类型从容器中查找可用对象。
- 举例:如果想将jdbc连接对象放入Spring容器,我们无法修改Connection源码添加@Component,此时就需要使用将@Bean该对象放入Spring容器
@Import
- 作用:如果配置过多,会有多个配置类,该注解可以为主配置类导入其他配置类
- 位置:主配置类上方