注解的使用之Component注解的使用
2021/7/14 6:06:32
本文主要是介绍注解的使用之Component注解的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
通过spring的注解完成java对象的创建,属性。代替xml文件
实现步骤:
1.加入依赖
2.创建类,在类中加入注解
package com.example.ba01; import org.springframework.stereotype.Component; /*@Component:创建对象,等同于<bean>的功能 * 属性:value 就是对象的名称,也是bean的id值 * value的值是唯一的,创建的对象在整个spring容器中就一个 * 位置:在类的上面 * * @Component(value = "myStudent")等同于 * <bean id = "myStudent" class = "com.example.ba01.Student" /> * */ @Component(value = "myStudent") public class Student { private String name; private Integer age; public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
3.创建spring的配置文件----声明组件扫描器的标签,指名注解在你的项目中的位置
<?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 https://www.springframework.org/schema/context/spring-context.xsd"> <!--声明组件扫描器(component-scan),组件就是java对象 base-package:指定注解在你的项目中的包名 component-scan工作方式:spring会扫描遍历base-package指定的包, 把包中和子包中的所有类,找到类中的注解,按照注解的功能创建对象,或给属性赋值。 --> <context:component-scan base-package="com.example.ba01"/> </beans>
4.使用注解创建对象,创建容器ApplicationContext
public class MyTest01 { @Test public void test01(){ String config = "applicationContext.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(config); //从容器中获取对象 Student student = (Student) ctx.getBean("myStudent"); System.out.println(student); } }
这篇关于注解的使用之Component注解的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升
- 2024-05-08代码报错不用愁,CodeGeeX一键完成代码修复、错误解释的功能上线了!
- 2024-05-08今天开始程序员不用再发愁写commit message了,全部由CodeGeeX自动完成!