注解的使用之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注解的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程