Home  >  Article  >  Java  >  What is the configuration method of java in springboot

What is the configuration method of java in springboot

王林
王林forward
2023-05-13 15:55:061368browse

1. Create User entity class.

@Data
public 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>();
  //模拟数据库查询
  for(int i = 1;i <p><strong>3. Write UserService to implement User data operation business logic. </strong></p>
<pre class="brush:php;toolbar:false">@service
public class UserService{
 @Autowired//注入Spring容器中的bean对象
 private UserDao userDao;
 public List<user> queryUserList() {
  //调用userDao中的方法进行查询。
  return this.userDao.queryUserList();
 } 
}</user>

4. Write SpringConfig to instantiate the Spring container.

@Configuration//通过该注解来表明该类是一个spring的配置,相当于一个xml文件。
//配置扫描包。
@ComponentScan(basePackages = "cn.my.springboot.javaconfig")
public class SpringConfig {
 @Bean//通过该注解来表明是一个Bean对象,相当于xml中的<bean>
 public UserDao getUserDao() {
  return new UserDao();//直接new对象作演示。
 }
}</bean>

5. Write a test method to start the Spring container.

public class Test {
 public static void main(String[] args) {
  //通过java配置来实例化Spring容器。
  AnnotationConfigApplicationContext context = new 
  AnnotationConfigApplicationContext(SpringConfig.class); 

  //在Spring容器中获取bean对象
  UserService userService = context.getBean(UserService.class);

  //调用对象中的方法
  List<user> list = userService.queryUserList();
  for(User user : list) {
   System.out.println(user.getUsername() + "|" user.getPassword() + "|" user.getAge());
  //销毁该容器
  context.destroy;
  }
 }
}</user>

Test results:

What is the configuration method of java in springboot

You can use java code to perfectly replace the XML configuration file.

As for the structure, please don’t be clear, it’s all in the eye of the beholder.

The above is the detailed content of What is the configuration method of java in springboot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete