summaryrefslogtreecommitdiff
path: root/spring-framework/04-basic-no-xml-java-configuration/src/main/java/com/example/spring/App.java
blob: 1e613c661ab3e0e96dc4a36493c6747c7726819a (plain)
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
package com.example.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class App {

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		ApplicationContext ctx = new AnnotationConfigApplicationContext(App.class);

		MathsUser mathsUser = ctx.getBean(MathsUser.class);

		mathsUser.doTask();
	}

	@Bean
	public Maths maths() {
		Maths maths = new Maths();
		maths.setB(100);

		return maths;
	}

	@Bean
	public MathsUser mathsUser() {
		MathsUser mathsUser = new MathsUser();

		/*
		 * What would the maths() return? Would it be the Spring managed bean or what
		 * would be returned when the maths() method is directly invoked?
		 * 
		 * @Bean can be used with classes annotated with @Component tool.
		 * 
		 * In a class annotated with @Configuration, maths() return the Spring managed bean.
		 *  
		 * In a class annotated with @Component, what is returned by maths() is not the
		 * Spring managed bean, but what would be returned when the maths() method is directly invoked.
		 * 
		 * For more details, look at the 'Full @Configuration vs “lite” @Bean mode?' description
		 * found in the 'Core Technologies' section of the Spring Framework Reference documentation.  
		 */
		mathsUser.setMaths(maths());

		return mathsUser;
	}
}