bean
-
使用注解开发需要导入spring的一系列包;
-
需要再配置文件中加一个约束:context;
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
-
配置扫描组件
<!--自动扫描指定包下的注解--> <context:component-scan base-package="com.chao.demo"/>
-
编写代码:
//等价于:<bean id="user" class="com.chao.demo.User"/> /* @Component : 组件 bean @Controller :web层 @Service : service层 @Repository :dao层 */ @Component("user") public class User { public String name = "晁文利1号"; }
IOC注入
- 可以不用提供set方法,可以直接在属性名上添加一个@Values(值);
@Controller("user2")
public class User2 {
// <bean class="com.kuang.demo.User2" id="user2">
// <property name="name" value="秦疆2号"/>
// </bean>
@Value("晁文利")
private String name;
public String getName() {
return name;
}
}
- 加入有set呢,直接在set方法上面加上@Values(值);
@Controller("user2")
public class User2 {
// <bean class="com.kuang.demo.User2" id="user2">
// <property name="name" value="秦疆2号"/>
// </bean>
private String name;
public String getName() {
return name;
}
@Value("晁文利")
public void setName(String name) {
this.name = name;
}
}
自动装配【了解】
@Component("user3")
public class User3 {
@Value("晁文利3号")
public String name;
/*
@Autowired //自动注入按照类型匹配,如果存在两个自动匹配对象的值,则无法匹配;
@Qualifier("dog1")
public Dog dog;
*/
//不是spring的包,是annotation的包;
@Resource(name = "dog1")
public Dog dog;
}
作用域【了解】
@Scope("prototype") //Spring默认是单例模式的,如果要改成多例模式,加上作用域prototype即可
@Scope("prototype")
@Component("user3")
public class User3 {
}
AOP
回看AOP注解实现
注解和XML对比
- xml可以适用于任何场景,结构清晰,推荐使用。
- 注解不是自己提供的类,存在局限性;好处:开发简单,方便
注解xml可以整合开发
xml和注解的最佳实践:
- xml管理bean
- 注解完成属性的注入