Home > Java > javaTutorial > body text

What is the java configuration method in springboot

WBOY
Release: 2023-05-04 23:19:05
forward
1459 people have browsed it

1. Create User entity class.

@Data
public class User {
 private String username;
 private String password;
 private Integer age;
}
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template