Spring入门

Spring依赖注入

Java注解(Annotation)

在spring的使用中,我们需要使用Java注解方法即如 @Service 来完成

Java注解不像普通的注释,它是可以在编译、运行过程中被读取的。

在Spring中IoC是极其重要的组件,其提供依赖注入来完成。

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

ApplicationContext context = new AnnotationConfigApplicationContext("test.modo");

以此来获取test.modo下所有的Bean

而我们通过在类前加上Bean注解,就可以标记Bean以此来通过IoC实现类

Bean注解:

  • org.springframework.stereotype.Service
  • org.springframework.stereotype.Component
  • org.springframework.stereotype.Controller
  • org.springframework.stereotype.Repository

@Component 注解是通用的 Bean 注解,其余三个注解都是扩展自 Component
@Service 正如这个名称一样,代表的是 Service Bean
@Controller作用于 Web Bean
@Repository作用于持久化相关 Bean

大致如下(省略部分代码)

SongServiceImpl.java
package fm.douban.service.impl;
 import org.springframework.stereotype.Service;
 import fm.douban.service.SongService;
 import fm.douban.model.Song;
 import java.util.*;
 @Service
 public class SongServiceImpl implements SongService {
 private static Map songMap = new HashMap<>();
 static {
       Song song = new Song();
       song.setId("001");
       song.setSubjectId("s001");
       song.setLyrics("…");
       song.setName("成都");
       songMap.put(song.getId(), song);
   }
 @Override
   public Song get(String songId) {
       return songMap.get(songId);
   }
 }
Application.java
package fm.douban;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 import fm.douban.service.SongService;
 import fm.douban.model.Song;
 /**
 Application
 */
 public class Application {
 public static void main(String[] args) {
 ApplicationContext context = new AnnotationConfigApplicationContext("fm.douban");    
   SongService songService = context.getBean(SongService.class);    
   Song song = songService.get("001");    
   System.out.println("得到歌曲:"+song.getName());    
 }
 } 

依赖注入2

前面的步骤,我们完成了IoC的启动,而接下来,我们才是真正的完成依赖注入

@Autowired 注解可以帮助我们直接从外部import使用Bean无需再次写明

 package fm.douban.service.impl;
import fm.douban.model.Song;
import fm.douban.model.Subject;
import fm.douban.service.SongService;
import fm.douban.service.SubjectService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 @Service
public class SubjectServiceImpl implements SubjectService { 
@Autowired
private SongService songService;//这里直接通过Autowired调用了内部的Service

//缓存所有专辑数据
private static Map<String, Subject> subjectMap = new HashMap<>();
static {
    Subject subject = new Subject();
    subject.setId("s001");
    subjectMap.put(subject.getId(), subject);
}

@Override
public Subject get(String subjectId) {
    Subject subject = subjectMap.get(subjectId);
    //调用 SongService 获取专辑歌曲
    List<Song> songs = songService.list(subjectId);
    subject.setSongs(songs);
    return subject;
}

}