1. Create the User entity class.
@Datapublic class User { private String username; private String password; private Integer age;}2. Create UserDao to simulate database interaction.
public class UserDao{ public List<User> queryUserList() { List<User> result = new ArrayList<User>(); //Simulate database query for(int i = 1;i < 10; i++) { User user = new User(); user.setUsername("username_" + i); user.setPassword("password" + i); user.setAge(i); result.add(user); } return result; }}3. Write UserService to implement the business logic of User data operation.
@servicepublic class UserService{ @Autowired//Inject the bean object private UserDao userDao; public List<User> queryUserList() { //Calling the method in userDao for query. return this.userDao.queryUserList(); } }4. Write SpringConfig for instantiating Spring containers.
@Configuration//This annotation shows that the class is a spring configuration, equivalent to an xml file. //Configure the scan package. @ComponentScan(basePackages = "cn.my.springboot.javaconfig")public class SpringConfig { @Bean//This annotation is a Bean object, which is equivalent to <bean> public UserDao getUserDao() { return new UserDao();//Directly demonstrate the new object. }}5. Write a test method to start Spring container.
public class Test { public static void main(String[] args) { //Instantiate the Spring container through Java configuration. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); //Get the bean object in the Spring container UserService userService = context.getBean(UserService.class); //Calling the method in the object List<User> list = userService.queryUserList(); for(User user: list) { System.out.println(user.getUsername() + "|" user.getPassword() + "|" user.getAge()); //Destroy the container context.destroy; } }}Test results:
A perfect alternative to XML configuration files can be used with java code.
As for the structure, please be unclear, it means that people have different opinions.
The above article "Java configuration method (example explanation) of springboot" is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.