spring-注解开发
1. 准备阶段
1.1 使用注解必须引入AOP的包
1.2 在配置文件中加入context约束
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
1.3 开启注解支持
<context:annotation-config/>
1.4 指定需要扫描哪个包下的注解
<context:component-scan base-package="com.lv"/>
1.5 最终的 spring 配置文件 applicationContext.xml
<?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 http://www.springframework.org/schema/context/spring-context.xsd"> <!--指定要扫描的包,这个包下的注解就会生效--> <context:component-scan base-package="com.lv"/> <context:annotation-config/> </beans>
2 编写实体类
package com.lv.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; //等价于<bean id="user" class="com.lv.pojo.User"/> @Component //设置Bean的作用域 @Scope("prototype") public class User { //等价于<property name="name" value="大傻瓜"> @Value("大傻瓜") public String name; //等价于<property name="name" value="小傻瓜"> @Value("小傻瓜") public void setName(String name) { this.name = name; } }
3 测试
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = context.getBean("user", User.class); System.out.println(user.name); }
4 执行结果
5 实例中出现的注解
@Component 写在类名上,表示将这个类注册到IOC容器中,相当于配置文件中 <bean id="user" class="com.lv.pojo.User"/>
@Scope("prototype") 写在类名上,设置Bean的作用域,括号内的参数填作用域,相当于<bean id="user" class="com.lv.pojo.User" scope="propertype"/>
@Value("大傻瓜") 写在属性或者set方法上,设置属性的值,相当于<property name="name" value="大傻瓜">,如果set方法和属性上都写了,set方法上的优先级更高
6 补充注解
@Controller 写在 controller层
package com.lv.controller; import org.springframework.stereotype.Controller; @Controller public class UserController { }
@Repository 写在 dao层
package com.lv.dao; import org.springframework.stereotype.Repository; @Repository public class UserDao { }
@Service 写在 service层
package com.lv.service; import org.springframework.stereotype.Service; @Service public class UserService { }
以上三个注解功能与@Component 完全一样,只是写的位置不同而已
7 与 Bean装配相关的注解在下面这篇博客中
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律