崇之他和她

导航

day03602spring5注解

spring 注解开发 舍弃xml springboot基础

下面是一个测试类

import com.ConfingA;
import com.TestConfigA;
import com.Zhq;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @ Author     :wwwzhqwww
 * @ Date       :Created in 17:05 2021/2/25
 * @ Description:
 * @ Modified By:
 * @Version: $version$
 */
public class myTest {

    @Test
    public void test(){//读取xml方式  在xml中开启扫描组件以及开启注解支持  在Zhq实体类上增加注解@Component  在set方法上增加@Value 注解设置属性默认值
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Zhq zhq = context.getBean("zhq",Zhq.class);
        System.out.println(zhq.getName());
    }

    @Test
    public void testConfigA(){//测试不用xml配置用注解实现扫描类
        ApplicationContext context = new AnnotationConfigApplicationContext(ConfingA.class);
        TestConfigA tta = context.getBean("tta",TestConfigA.class);
        tta.setAge(22);
        System.out.println(tta.getAge());

    }
}

基于注解Configuration的组件加载类

package com;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @ Author     :wwwzhqwww
 * @ Date       :Created in 17:10 2021/2/25
 * @ Description:
 * @ Modified By:
 * @Version: $version$
 */
@ComponentScan("com")//扫描所有com下组件  相当于 <context:component-scan base-package="com"/>
@Configuration//此注解将普通类变成组件加载类,其中所有被spring接管
public class ConfingA {
    @Bean//相当于xml文件中的bean标签  方法名 = id  返回类型 = class
    public TestConfigA tta(){
        return new TestConfigA();// 返回值表示要注入的对象
    }
}

测试用普通实体类

package com;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @ Author     :wwwzhqwww
 * @ Date       :Created in 17:12 2021/2/25
 * @ Description:
 * @ Modified By:
 * @Version: $version$
 */
@Component
public class TestConfigA {

    private int age;

    public int getAge() {
        return age;
    }

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

posted on 2021-02-25 20:01  崇之他和她  阅读(57)  评论(0编辑  收藏  举报