欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring注解驱动

程序员文章站 2022-05-29 13:37:23
...

Spring注解

1、Spring注解如下图所示:

Spring注解驱动

2、xml配置方式

实体类

public class Person {
    private String name;

    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Person(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person" class="com.lyc.entity.Person">
        <property name="age" value="10"/>
        <property name="name" value="111"/>
    </bean>

</beans>

测试注入

public class MainTest {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
    }
}

结果:
Spring注解驱动

3、注解方式

定义配置类

//配置类===配置文件
@Configuration  //声明一个配置类,并告知Spring
public class MainCofig {

    //给容器注册一个bean,类型为返回值得类型,id默认是用方法作为id
    @Bean
    public Person person(){
        return new Person("2222","10");
    }
}

测试注入:

public class MainTest {

    public static void main(String[] args) {
        ApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(MainCofig.class);
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
    }
}

Spring注解驱动