使用类注解
- 开启包扫描
需要加入新的约束之后,才能开启包扫描。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<context:component-scan base-package="com.domain"></context:component-scan>
</beans>
- 使用注解注册bean
被扫描的包里面所有的类都会被扫描,当在类上有注解@Component时,把这个类注册为bean,如果这个类没有无参构造方法,将会在运行时报错。
@Component
public class Dog {
}
例如上面这个被管理类,ID将是dog,理由是对于被管理的类,类名将是ID名,不过在类名的第一个字母的大小写情况和第二个是一样的。如果上面这个类名字为DOg时,他的ID将是DOg。不过这些都是默认的情况,也可以自己设置ID名,比如@Component(“自定义ID名”)对于Component注解创建bean,和是一样的
对于@Controller、@Service、@Repository注解和component注解作用是一样的,只不过这三个标签分别表明在controller层、service层、dao层。
- 使用注解依赖注入
首先要开启属性注解
<context:annotation-config></context:annotation-config>
当开启属性注解时,在创建bean对象时会就检查属性们是否有相应的注解,然后按相应规则注入。
对于@AutoWire
此标签注入时表示的是自动装配,适用属性是自定义的bean对象,根据属性名查找bean,如果没有就根据类型。
不过也可以利用注解@Qualifier(value=“dog1”)指定是哪个ID名的bean。
对于@Value
此标签注入属性都是一些内置对象而且不是集合类型的,比如int,string,long,之间将值注入属性。
不过这种写法会把值写死,可以把值放到一个properties文件中,有利于修改和重复利用。
<context:property-placeholder location="classpath:demo.properties"/> //需要放在src目录下
@Value("${a}")
private String name;
@Value("${b}")
private int age;
在demo.properties文件书写以下内容
a=xy
b=24
而对于一些非集合类型的内置对象时,需要先将集合类型的数据配置到spring配置文件中。
<util:list id="names">
<value>a</value>
<value>ab</value>
</util:list>
<util:set id="ages">
<value>12</value>
<value>11</value>
</util:set>
在用value获取值时用#{@ID}作为参数
@Value("#{@names}")
private List<String> dogs;
@Value("#{@ages}")
private Set<Integer> ageIntegers;
- 一些其他注解
@Scope
这个注解修饰类,在Component注解下面修饰,表明此类是以什么模式创建。默认单例模式
@Component()
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@lazy
也是修饰类的注解,在component下修饰,加上此注解表明此类是懒加载
@PostConstruct
此注解修饰的是方法,表示该方法在该bean创建之后,立即执行。
@PreDestroy
此注解修饰的是方法,表示该方法在该bean即将销毁时,执行此方法。