2.1注解实现spring的Helloworld

戴着假发的程序员出品  抖音ID:戴着假发的程序员 欢迎关注

[查看视频教程]

[1]创建maven项目,添加依赖:

1 <dependency>
2     <groupId>org.springframework</groupId>
3     <artifactId>spring-context</artifactId>
4     <version>5.1.3.RELEASE</version>
5 </dependency>

[2]准备两个DAO接口和实现类:

接口:

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 public interface IAutorDAO {
 7     public String get();
 8 }
 9 /**
10  * @author 戴着假发的程序员
11  *  
12  * @description
13  */
14 public interface IArticleDAO {
15     public int save(String title);
16 }

实现类:

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 public class ArticleDAO implements IArticleDAO {
 7     @Override
 8     public int save(String title) {
 9         System.out.println("ArticleDAO-save->保存文章:"+title);
10         return 1;
11     }
12 }
13 /**
14  * @author 戴着假发的程序员
15  *  
16  * @description
17  */
18 public class AuthorDAO  implements IAutorDAO {
19     @Override
20     public String get() {
21         return "戴着假发的程序员";
22     }
23 }

[3]准备ArticleService

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 public class ArticleService {
 7     private IAutorDAO autorDAO;
 8     private IArticleDAO articleDAO;
 9 
10     public void setAutorDAO(IAutorDAO autorDAO) {
11         this.autorDAO = autorDAO;
12     }
13 
14     public void setArticleDAO(IArticleDAO articleDAO) {
15         this.articleDAO = articleDAO;
16     }
17 
18     public int save(String title){
19         String author = autorDAO.get();
20         System.out.println("ArticleService-save:");
21         System.out.println("author:"+author);
22         return articleDAO.save(title);
23     };
24 }

[4]添加一个配置类,并且在配置类中使用@Bean的方式配置上面的是三个类:

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 @Configuration
 7 public class AppConfig {
 8     //配置 ArticleDAO对象
 9     @Bean
10     public IArticleDAO articleDAO(){
11         return new ArticleDAO();
12     }
13     //配置 AuthorDAO
14     @Bean
15     public IAutorDAO authorDAO(){
16         return new AuthorDAO();
17     }
18     //配置ArticleService对象
19     @Bean
20     public ArticleService articleService(){
21         ArticleService articleService = new ArticleService();
22         //注入对应的属性
23         articleService.setArticleDAO(articleDAO());
24         articleService.setAutorDAO(authorDAO());
25         return articleService;
26     }
27 }

[5]测试:

1 @Test
2 public void testAnnotation(){
3     ApplicationContext ac =
4             new AnnotationConfigApplicationContext(AppConfig.class);
5     ArticleService bean = ac.getBean(ArticleService.class);
6     bean.save("spring应用手册");
7 }

posted @ 2020-10-07 08:49  戴着假发的程序员0-1  阅读(183)  评论(0编辑  收藏  举报