Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the configuration mode of java in springboot

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

今天小编给大家分享一下springboot中java配置方式是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

1.创建User实体类。

@Datapublic class User { private String username; private String password; private Integer age;}

2.创建UserDao用于模拟数据库交互。

public class UserDao{ public List queryUserList() { List result = new ArrayList(); //模拟数据库查询 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.编写UserService用于实现User数据操作业务逻辑。

@servicepublic class UserService{ @Autowired//注入Spring容器中的bean对象 private UserDao userDao; public List queryUserList() { //调用userDao中的方法进行查询。 return this.userDao.queryUserList(); } }

4.编写SpringConfig用于实例化Spring容器。

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

5.编写测试方法用于启动Spring容器。

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 list = userService.queryUserList(); for(User user : list) { System.out.println(user.getUsername() + "|" user.getPassword() + "|" user.getAge()); //销毁该容器 context.destroy; } }}

测试结果:

可以使用java代码完美的替代XML配置文件。

以上就是"springboot中java配置方式是什么"这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注行业资讯频道。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report