注解开发
1、注意
-
导入约束-------------------->context约束
<?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.xsd">
</beans>
-
配置注解支持 :
<context:annotation-config/>
2、自动装配
@Autowired
注释:
-
因为apple是一个实体类,它也需要现在applicationContext.xml文件中先注册,才能被自动装配,
-
但是普通的属性,无法自动装配是因为没有被注册,
-
需要与applicationContext.xml文件的id匹配
-
可以设置值@Autowired(required = false)------->表示这个对象可以为空
<bean id="user" class="com.packet.pojo.User"/>
<bean id="apple" class="com.packet.pojo.Apple"/>
@Qualifier
@Autowired
@Qualifier(value = "apple")
private Apple apple;
可以自定义设置名字,与其中的<bean>进行匹配---------------->自己指定一个bean与它匹配
@Resource
-
更高级,先通过id找,如果匹配不上,再通过class找
-
用的较少
-
也是自动装配的
-
@Autowired是通过byclass的方式,,,@Resource是先通过byid,如果找不到,再通过byclass的方式,如果两个都找不到就会报错
3、使用注解开发
注意
-
导入约束-------------------->context约束
<?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.xsd">
</beans>
-
配置注解支持 :
<!-- 扫面全部的包-->
<context:component-scan base-package="com.packet"/>
<!-- 实现自动装配-->
<context:annotation-config/>
@Component
@Component
@Data
public class User {
@Value("皮夹子")
private String name;
}
-
等效于
-
<bean id="user" class="com.packet.pojo.User"/>
-
Value表示对属性赋值
-
Value也可以放在set方法上,效果是一样的
-
@Component @Data public class User { private String name; @Value("皮夹子") public void setName(String name) { this.name = name; } }
-
简单的属性可以直接注入,但是复杂的就不行,需要自己在配置文件中手动输入
衍生注解
-
mapper【@Repository】
-
service【@Sevice】
-
controller【@Controller】
-
功能都是一样的,都是代表将某个类注册到Spring中,装配Bean