Defining Spring Boot Java Beans
Defining Beans in Java Code
Creating a Bean with the @Bean Annotation
Hoge.java
package sample.springboot;
public class Hoge {
private String name;
public Hoge(String name) {
this.name = name;
}
@Override
public String toString() {
return "Hoge [name=" + name + "]";
}
}
Main.java
package sample.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
Hoge h = ctx.getBean(Hoge.class);
System.out.println(h);
}
}
@Bean
public Hoge getHoge() {
System.out.println("Main#getHoge()");
return new Hoge("hoge");
}
}
Result
Main#getHoge()
Hoge [name=hoge]
Explanation
- Annotate a method with
@Beanto create a Bean instance through that method. - You can define this type of Bean in a class annotated with
@Configuration.@SpringBootApplicationhas the same effect as applying@Configuration.
Creating a Separate Class Annotated with @Configuration
Annotate a class with @Configuration and a method with @Bean to define a method that creates a Bean of any class.
HogeProvider.java
package sample.springboot;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HogeProvider {
@Bean
public Hoge getHoge() {
System.out.println("HogeProvider#getHoge()");
return new Hoge("hoge provider");
}
}
Main.java
package sample.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
Hoge h = ctx.getBean(Hoge.class);
System.out.println(h);
}
}
}
Result
HogeProvider#getHoge()
Hoge [name=hoge provider]