配置类

package com.kuang.pojo;

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

public class User {
    public String getName() {
        return name;
    }
    @Value("烛花红")
    public void setName(String name) {
        this.name = name;
    }

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

    private String name;
}

配置文件

package com.kuang.config;

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

@Configuration//这个也会被spring容器托管,因为他本身就是一个@Component,@Configuration代表一个配置类,就和我们之前看到bean.xml一样
@Import(Kuangconfig2.class)
public class Kuangconfig {
    //注册一个Bean就相当于我们之前写的一个Bean标签。
    //这个方法的名字就相当于Bean标签中的ID属性
    //返回值就相当于Bean标签当中的Class属性
    @Bean
    public User user(){
        return new User();//返回要注入到Bean中的对象!
    }
}

测试类

import com.kuang.config.Kuangconfig;
import com.kuang.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Mytest {
    public static void main(String[] args) {
        //如果使用了@Configuration去配置Bean,我们就只能使用AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context =new AnnotationConfigApplicationContext(Kuangconfig.class);
        User user =(User) context.getBean("user");
        System.out.println(user.toString());
    }
}
posted on 2021-10-14 21:44  比企苦  阅读(29)  评论(0编辑  收藏  举报