08.02.2020, 17:36. Показов 2439. Ответов 4
Читал и копировал поэтапно код отсюда
Кликните здесь для просмотра всего текста
https://spring-projects.ru/guides/lessons/lesson-2/
Собственно после попытки добавления Autowired бина в контекст AnotherConfiguration(поправьте, если не прав: для создания бина GreetingService из AnotherConfiguration добавляем аннотацию, чтобы в этом контексте иметь доступ к бину)
Поле подсвечивает, но компилирует. Вот стэк
Кликните здесь для просмотра всего текста
| Code |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
| ...
581 [main] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected element of bean 'anotherConfiguration': AutowiredFieldElement for lessons.services.GreetingService lessons.AnotherConfiguration.greetingService
584 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'greetingServiceImpl'
588 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: lessons.services.GreetingService lessons.AnotherConfiguration.greetingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingServiceImpl' defined in file [\springIoC1\target\classes\lessons\services\GreetingServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at lessons.starter.Starter.main(Starter.java:19)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: lessons.services.GreetingService lessons.AnotherConfiguration.greetingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingServiceImpl' defined in file [\springIoC1\target\classes\lessons\services\GreetingServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 12 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingServiceImpl' defined in file [springIoC1\target\classes\lessons\services\GreetingServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 14 more
Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:156)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 21 more
589 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6276ae34: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,lessonsConfiguration,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,anotherConfiguration,greetingServiceImpl,beanWithDependency,gServiceName,asyncCommand,commandManager]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: lessons.services.GreetingService lessons.AnotherConfiguration.greetingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingServiceImpl' defined in file [\springIoC1\target\classes\lessons\services\GreetingServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at lessons.starter.Starter.main(Starter.java:19)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: lessons.services.GreetingService lessons.AnotherConfiguration.greetingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingServiceImpl' defined in file [\springIoC1\target\classes\lessons\services\GreetingServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 12 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingServiceImpl' defined in file [\springIoC1\target\classes\lessons\services\GreetingServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 14 more
Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'context' is required for bean 'greetingServiceImpl'
at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:156)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 21 more
Process finished with exit code 1 |
|
Кроме этих классов есть и другие, но, думаю, они не связаны с проблемой
AnotherConfiguration
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| package lessons;
import lessons.services.BeanWithDependency;
import lessons.services.GreetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AnotherConfiguration {
@Autowired GreetingService greetingService;
@Bean
BeanWithDependency beanWithDependency() {
// что-нибудь делаем с greetingService
return new BeanWithDependency();
}
} |
|
LessonsConfiguration
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| package lessons;
import lessons.services.CommandManager;
import lessons.services.GreetingService;
import lessons.services.GreetingServiceImpl;
import org.springframework.context.annotation.*;
/**
* Конфигурационный класс Spring IoC контейнера
* Класс с аннотацией @Configuration говорит о том, что он является источником определения бинов
*/
@Configuration
@ComponentScan
@Import(AnotherConfiguration.class)
public class LessonsConfiguration {
@Bean
@Scope("prototype")
public Object asyncCommand() {
return new Object();
}
@Bean
public CommandManager commandManager() {
// возвращаем новую анонимную реализацию CommandManager
// с новым объектом
return new CommandManager() {
@Override
protected Object createCommand() {
return asyncCommand();
}
};
}
@Bean(name = "gServiceName")
@Description("Текстовое описание бина greetingService")
GreetingService greetingService() {
return new GreetingServiceImpl();
}
} |
|
GreetingServiceImpl
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| package lessons.services;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype") // область видимости бинов контекста
public class GreetingServiceImpl implements GreetingService {
private ApplicationContext context;
@Override
public String sayGreeting() {
return "Greeting, user!";
}
@Required
public void setContext(ApplicationContext context) {
this.context = context;
}
} |
|
Starter.java
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| package lessons.starter;
import lessons.LessonsConfiguration;
import lessons.services.BeanWithDependency;
import lessons.services.GreetingService;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
public class Starter {
private static final Logger logger = LogManager.getLogger(Starter.class);
public static void main(String[] args) {
BasicConfigurator.configure();
logger.info("Starting configuration...");
AbstractApplicationContext context = new AnnotationConfigApplicationContext(LessonsConfiguration.class);
GreetingService greetingService = context.getBean(GreetingService.class);
BeanWithDependency withDependency = context.getBean(BeanWithDependency.class);
logger.info(greetingService.sayGreeting());
logger.info(withDependency.printText());
context.registerShutdownHook();
/*
Можно инициализировать ioc контекст таким образом, постепенно добавляя классы
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(LessonsConfiguration.class);
context.refresh();
*/
}
} |
|