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 of java in springboot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

这篇文章主要讲解了"springboot中java的配置方式是什么",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"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的配置方式是什么"的内容了,经过本文的学习后,相信大家对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

Internet Technology

Wechat

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

12
Report