Home >Java >javaTutorial >What is the java configuration method in springboot

What is the java configuration method in springboot

WBOY
WBOYforward
2023-05-04 23:19:051461browse

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 java configuration method in springboot

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

The above is the detailed content of What is the java configuration method 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