简体   繁体   English

如何在 Spring 引导中创建不可变和 singleton class?

[英]How to create immutable and singleton class in Spring boot?

I have a person model class that needs to be immutable and singleton. I need to autowire from my service class but getting an error.我有一个需要不可变的人 model class 和 singleton。我需要从我的服务 class 自动装配但出现错误。

So is there any way to create a singleton immutable class in spring boot?那么有什么办法可以在spring引导中创建一个singleton不可变的class呢? where i can set values in person (via autowire) and use the same in the entire application.我可以亲自设置值(通过自动装配)并在整个应用程序中使用相同的值。

I have just started learning spring-boot. I searched on google and found the solution with Lombok but somehow it didn't work for me.我刚刚开始学习 spring-boot。我在谷歌上搜索并找到了 Lombok 的解决方案,但不知何故它对我不起作用。

My person model:我的人 model:

    @Value
    @Builder
    @AllArgsConstructor(access = AccessLevel.PRIVATE) 
    @Component
    public final class Person {
        private final String firstName;
        private final String lastName;
    }


//My service class
@Component
public class ArgumentReadingService {
    
    @Autowired
    Person person;
    
    public void readArguments() {
        
        person = Person.builder().firstName("Hello").build();
        
        System.out.println("name : "+person.getFirstName());
        
    }

Error:错误:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-03-10 17:52:29.197 ERROR 8824 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person' defined in file [C:\Users\User\Desktop\WorkSpace\Orion.Strat1.bidAsk_Stp\target\classes\orion\model\Person.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [orion.model.Person]: No default constructor found; nested exception is java.lang.NoSuchMethodException: orion.model.Person.<init>()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1316) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:917) ~[spring-context-5.3.4.jar:5.3.4]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:582) ~[spring-context-5.3.4.jar:5.3.4]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) [spring-boot-2.4.3.jar:2.4.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.4.3.jar:2.4.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) [spring-boot-2.4.3.jar:2.4.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) [spring-boot-2.4.3.jar:2.4.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311) [spring-boot-2.4.3.jar:2.4.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) [spring-boot-2.4.3.jar:2.4.3]
    at com.orion.Application.main(Application.java:20) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [orion.model.Person]: No default constructor found; nested exception is java.lang.NoSuchMethodException: orion.model.Person.<init>()
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83) ~[spring-beans-5.3.4.jar:5.3.4]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1308) ~[spring-beans-5.3.4.jar:5.3.4]
    ... 17 common frames omitted
Caused by: java.lang.NoSuchMethodException: orion.model.Person.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_191]
    at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_191]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78) ~[spring-beans-5.3.4.jar:5.3.4]
    ... 18 common frames omitted

This configuration class and that annotation will provide you always with that Person Bean此配置 class 和该注释将始终为您提供该 Person Bean

@Configuration
public class ServerConfig extends
{

    @Bean
    private Person getPerson(){
        return new Person("name", "lastName");
    }

Now it will be available everywhere for autowiring.现在它将随处可用于自动装配。

As the comments note however, it seems strange to use a model class as a Singleton.然而,正如评论所指出的,使用 model class 作为 Singleton 似乎很奇怪。

Adding some more info for the readers,为读者添加更多信息,

Look at this question for more clarity看看这个问题更清楚
SpringBoot - @Configuration creates a singleton bean SpringBoot - @Configuration 创建一个 singleton bean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM