对于java bean的定义和依赖配置,使用xml文件真心是不方便。
今天学习如何用注解,解决bean的定义和注入。
常用注解:
1、自动注入:@Resources,@Autowired
2、Bean定义:@Component、@Repository、@Service 和 @Constroller
@Component是个泛化概念,可以用在任何层次。如果是web开发,尽量用@Repository、@Service 和 @Constroller
Demo:
以丁磊养猪为例,Pig和DingLei两个类
1、Pig类,以@Component定义为bean

@Component public class Pig { private Double weight; private String color; public Pig(){ this.weight = 55.8; this.color = "black"; } public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String toString(){ return weight + " kg " + color + " pig!"; } }
2、DingLei类,以@Component定义为bean,同时用@Autowired注入依赖pig

@Component public class DingLei { @Autowired private Pig pig; public Pig getPig() { return pig; } public void setPig(Pig pig) { this.pig = pig; } public String toString(){ return "Dinglei has a " + pig.toString(); } }
3、bean.xml文件中,配置包扫描,注解才生效
<context:annotation-config/> :启用注释驱动自动注入
<context:component-scan/>:对类包进行扫描以实施注释驱动 Bean 定义,同时隐式启用注释驱动自动注入。因此,配置这个就可以

<?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/spring-context-3.0.xsd"> <!-- <context:annotation-config/> --> <context:component-scan base-package="anotation"/> </beans>
4、测试类

public class TestAnotation { @SuppressWarnings("resource") public static void main(String[] arg) { ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); DingLei dingLei = (DingLei) context.getBean("dingLei"); System.out.println( dingLei.toString() ); } }
5、运行测试类,可以看到输出。说明注解成功定义bean,并成功完成注入
信息: Loading XML bean definitions from class path resource [bean.xml] Dinglei has a 55.8 kg black pig!
参考:
谢谢无私分享的伙伴,写的非常详细的一篇:Spring注解详解
---
开心工作,认真生活;回望来时路,脚印三两,笑声无数...
开心工作,认真生活;回望来时路,脚印三两,笑声无数...
标签:
springMVC
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?