Spring使用纯JAVA开发

JavaConfig实现配置

前言:使用这个就不需要再去写配置文件了,直接全部使用注解来进行开发

先看一下整体的结构

在这里插入图片描述

TestConfig.java

package com.zkw.config;

import com.zkw.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
//@ComponentScan("com.zkw.pojo")
@Import(TestConfig2.class)
public class TestConfig {
    
    
    @Bean
    public User getUser(){
    
    
        return new User();
    }
}

@Configuration: 这个也会Spring容器托管,注册到容器中,因为它本身是一个@Component。另外 @Configuration 代表这是一个配置类,和我们之前所写的ApplicationContext.xml文件是一个东西。

@Import(xxx.class) 这个就是把多个配置文件融合在一起。

@Bean:注册一个bean,就相当于ApplicationContext.xml文件中的一个bean标签,这个方法的名字getUser就是bean标签中的 id,这个方法的返回值,就相当于bean标签中的class属性。

注册bean还有一种方法以我的为例:

User.java中使用@component这个注解让这个类被Spring容器托管,然后在TestConfig.java配置类里边,使用@ComponentScan(“com.zkw.pojo”)扫描这个包,这个也可以实现bean的注册,只不过此时的iduser


User.java

package com.zkw.pojo;

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

//@Component
public class User {
    
    

    @Value("Four Anger Man")
    private String name;

    public String getName() {
    
    
        return name;
    }

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

MyTest.java

import com.zkw.config.TestConfig;
import com.zkw.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    
    
    @Test
    public void TestUser(){
    
    
        //如果完全使用了配置类方式去做,我们只能通过AnnotationConfig 上下文来获取容器,通过配置类的Class来加载对象
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
        User getUser = context.getBean("getUser", User.class);
        System.out.println(getUser.getName());
    }
}

结果如下

在这里插入图片描述

Guess you like

Origin blog.csdn.net/fgets__/article/details/120742118