spring JavaConfig

147 阅读1分钟

实体类

package org.example.pojo;

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

public class User {
    private String name;

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

    public String getName() {
        return name;
    }

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

配置类

package org.example.config;

import org.example.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration//代表这是一个配置类,就和xml配置文件的作用是一样的。这个类也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
public class Config {

    @Bean//注册一个bean就相当于xml配置文件中的bean标签。方法名就相当于bean标签的id,方法的返回值就相当于bean标签的class属性
    public User getUser(){
        return new User();
    }
}

测试类

import org.example.config.Config;
import org.example.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        User user = context.getBean("getUser", User.class);
        System.out.println(user.toString());

    }
}