使用java的方式配置Spring(完全摒弃掉xml配置文件)

这种纯java的配置,不会出现xml的配置方式,在SpringBoot中随处可见

1、pojo类

@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("甜甜")
    public void setName(String name) {
        this.name = name;
    }

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

2、写一个注解类

TtConfig类

//这个也会被Spring容器托管,注册到容器中,因为本来就是一个@Component
//@Configuration代表这是一个配置类,就像beans.xml一样
@Configuration
@ComponentScan("com.tt.pojo")
@Import(TtConfig.class )
public class TtConfig {
    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User();//就是返回要注入到bean的对象
    }
}

3、测试类

import com.tt.pojo.TtConfig;
import com.tt.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

}
发布了51 篇原创文章 · 获赞 73 · 访问量 3700

猜你喜欢

转载自blog.csdn.net/qq_41256881/article/details/105428142