SoFunction
Updated on 2025-03-10

@Value failure problem in Springboot

@Value invalid in Springboot

During the process of writing a project, due to the rapid development of the project, the component or service is called in new, which can be troublesome, resulting in the @Value attribute in the component being invalid.

Interestingly, during the troubleshooting process, I used @Value in other services and it worked again, let's take a look.

In the end, there is only one truth, this.

Analysis of reasons

The instances produced by the new method will not be handed over to spring management, so they will not be proxyed.

In Spring framework, objects can be injected into other components or services by using annotations such as @Autowired or @Resource.

In this way, Spring will be responsible for managing the life cycle of the object and automatically inject relevant properties when needed.

If you want the @Value annotation to take effect, consider leaving the creation of the object to be managed by Spring.

1. Use @Component annotation

Mark an object as a Spring managed component:

@Component
public class MyObject {
    @Value("${}")
    private String myProperty;
    
    // getters and setters
}

Then wherever you need to use MyObject, inject it through the @Autowired annotation:

@Autowired
private MyObject myObject;

This way Spring will automatically inject property values ​​into the MyObject object.

2. If you do not want to mark an object as a component

You can use @Configuration and @Bean annotations to create objects:

@Configuration
public class MyConfig {
    @Value("${}")
    private String myProperty;

    @Bean
    public MyObject myObject() {
        MyObject myObject = new MyObject();
        (myProperty);
        return myObject;
    }
}

Then where you need to use MyObject, inject the configuration class through the @Autowired annotation and call its myObject() method to get the object:

@Autowired
private MyConfig myConfig;
...
MyObject myObject = ();

This also allows the @Value annotation to take effect and inject the property value into the MyObject object.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.