Instead of using XML configuration, you’ll use pure Java configuration, starting by writing a User entity class

package com.zhiying.pojo;

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

public class User {
    private String name;

    public String getName(a) {
        return name;
    }

    @value (" He Zhiying ")
    public void setName(String name) {
        this.name = name;
    }

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

The convention is to write a configuration file, but no configuration file is needed here, so write a Java configuration class

package com.zhiying.config;

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

// If there are multiple configuration files, you can also Import them with @import ()
// For example, to introduce MyConfig2 annotations, just write @import (myconfig2.class) above the class.

// This annotation will be hosted by Spring and registered in the container, which is a configuration class equivalent to our applicationContext.xml
@Configuration
public class MyConfig {

    The name in this method is the same as the id in the bean label
    @Bean
    public User user(a) {
        return new User(); // Returns the object to be injected into the bean}}Copy the code

test

import com.zhiying.config.MyConfig;
import com.zhiying.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(MyConfig.class);
        User user = (User) context.getBean("user"); System.out.println(user.getName()); }}Copy the code