前言
为什么要使用注解开发呢?
使用注解开发是为了让代码更加简洁轻巧,更方便于我们去管理和维护,因此我们需要学会注解开发。
在spring4之后,要使用注解开发,必须保证aop
的包导入
使用注解需要导入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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
</beans>
<!--指定要扫描的包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.cjh.pojo"/>
<context:annotation-config/>
使用@Component来开发
什么是Component
顾名思义,就是一个组件,放在类上,说明这个类被Spring管理了。
创建一个实体类
User
package com.cjh.pojo;
import org.springframework.stereotype.Component;
//等价于<bean id=“user” class=“com.cjh.pojo.User”/>
@Component
public class User {
public String name = "菜菜";
}
测试
import com.cjh.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user",User.class);
System.out.println(user.name);
}
}
结果
成功取出
等价于<bean id=“user” class=“com.cjh.pojo.User”/>
@Value
这个时候我们不直接给实体类赋值,使用注解赋值
User
public class User {
@Value("菜菜")
public String name;
}
结果
使用注解赋值@Value("xxxx")
相当于
<bean id="user" class="com.cjh.pojo.User">
<property name="name" value="菜菜"></property>
</bean>
衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!
dao @Repository
service@Service
controller@Controller
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
作用域@Scope
单例模式
@Scope("singleton")
原型模式
@Scope("prototype")
例子:
package com.cjh.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Scope("singleton")
//等价于<bean id=“user” class=“com.cjh.pojo.User”/>
//@Component:组件,放在类上,说明这个类被Spring管理了。
@Component
public class User {
//相当于 <bean id="user" class="com.cjh.pojo.User">
// <property name="name" value="菜菜"></property>
// </bean>
@Value("菜菜")
public String name;
小结
xml更加万能,适合于任何场合,维护极其方便
注解不是自己的类,使用不了,维护相对复杂
最佳实践:
xml用来管理bean
注解只负责完成属性的注入
我们在使用的过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下面的注解就会生效-->
<context:component-scan base-package="com.cjh"/>
<context:annotation-config/>