1、配置环境
-
在Spring4之后,要使用注解开发,必须要保证aop的包导入成功。

-
编写applicationContext.xml文件,还需要导入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"> <context:annotation-config/> </beans> -
编写实体类;
package com.beyond.pojo; import org.springframework.stereotype.Component; @Component //等价于<bean id="user" class="com.beyond.pojo.User"/> public class User { public String name="小明"; } -
注解**@Component**测试。
import com.beyond.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); } }
2、注解
2.1、属性的注入
-
编写实体类;
package com.beyond.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component //等价于<bean id="user" class="com.beyond.pojo.User"/> public class User { @Value("xiaoming") /* 相当于: <property name="name" value="xiaoming"/> public void setName(String name) { this.name = name; } */ public String name; } -
测试。
import com.beyond.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); } }
2.2、衍生注解
@Component有几个衍生的注解,我们在web开发中,会按照MVC三层架构分层。功能和@Component一样,都是表示将某个类注册到Spring中,只是习惯在不同的包使用不同的注解。
- dao【@Repository】
- service【@Service】
- controller【@Controller】
2.3、作用域
@Scope("")
小结:
xml与注解的特点:
- xml更加万能,适用于任何场合,维护简单方便;
- 注解不是自己的类使用不了,维护相对复杂。
xml与注解最佳实践:
- xml用来管理bean;
- 注解只完成属性的注入。
本文介绍了在Spring4之后如何使用注解进行开发,包括配置环境、注解的使用以及属性注入。通过在实体类上使用@Component注解,等价于XML中的bean定义。@Value注解用于属性注入,等价于XML中的property标签。此外,还讲解了@Component的衍生注解@Repository、@Service和@Controller,以及@Scope注解用于指定bean的作用域。总结了XML与注解的优缺点,并提出了最佳实践建议:XML管理bean,注解处理属性注入。
1088

被折叠的 条评论
为什么被折叠?



