为什么在Spring Boot中使用@Service构造型?

问题描述 投票:0回答:1

我知道@Service是@Component的一种,就像@Controller和@Repository一样。我也了解这些类型级别(类级别)的构造型可以帮助组件扫描在您的spring项目中选择不同的类型。

[我注意到我创建的用于处理业务逻辑的FileResourceManager的类在没有@Service的情况下也可以正常工作。我想更好地理解此构造型的作用以及为什么有用。如果可以帮助解释@Component,请这样做。

这是我试图添加@Service的示例类,因为它从从@Controller类收集的信息中准备文件,以获取与运行业务逻辑无关的软件包。>

@Service
public class FileResourceManager {

    private ConfigProp configProp;

    @Autowired
    private FormModel formModel;

    public FileResourceManager(FormModel formModel) {
        this.formModel = formModel;
    }

    public FormModel getformModel() {
        return formModel;
    }

    public void init() throws IOException {
        System.out.println("Initializing resources...");
        clearDirectories();
        writeTextboxToInputDirectories();
        writeMultifileToInputDirectories();
    }

    private void clearDirectories() throws IOException {
        configProp = configProp.getInstance();
        RwUtils.clearDirectory(System.getProperty("user.dir")+configProp.getProperty("input.dir")+"input/");
        RwUtils.clearDirectory(System.getProperty("user.dir")+configProp.getProperty("input.dir")+"file/");
    }

    private void writeMultifileToInputDirectories() throws IOException {

        configProp = configProp.getInstance();
        String inputDir = System.getProperty("user.dir")+configProp.getProperty("input.dir")+"input/";
        String fileDir = System.getProperty("user.dir")+configProp.getProperty("input.dir")+"file/";

        RwUtils.writeMultipartIntoFile(fileDir,formModel.getFile1());
        RwUtils.writeMultipartIntoFile(fileDir,formModel.getFile2());
        RwUtils.writeMultipartIntoFile(fileDir,formModel.getFile3());

        for (MultipartFile record: formModel.getFiles4()) {
            RwUtils.writeMultipartIntoFile(inputDir,record);
        }
    }

    private void writeTextboxToInputDirectories() throws IOException {
        configProp = configProp.getInstance();
        String inputDir = System.getProperty("user.dir")+configProp.getProperty("input.dir")+"input/";
        String fileDir = System.getProperty("user.dir")+configProp.getProperty("input.dir")+"file/";

        if(formModel.getFile1File().isEmpty()) RwUtils.writeStringToFile(fileDir+"file1.txt",formModel.getFile1Text());
        if(formModel.getFile2File().isEmpty()) RwUtils.writeStringToFile(fileDir+"file2.txt",formModel.getFile2Text());
        if(formModel.getFile3File().isEmpty()) RwUtils.writeStringToFile(fileDir+"file3.txt",formModel.getFile3Text());

        int i = 1;
        String recordFileStr;
        for (String record:formModel.getOldJsonText().split(";;;")) {
            recordFileStr = inputDir+"textboxRecord"+i+".json";
            RwUtils.writeStringToFile(recordFileStr,record);
            i++;
        }
    }

    // this class calls logic from a package that has no relation to spring-boot framework
    public void runBusinessLogic() throws IOException, InvalidEntryException {

        // logic

    }

    public void download(ZipOutputStream zippedOut) throws IOException {
        ConfigProp configProp = ConfigProp.getInstance();
        String downloadFormat = getformModel().getDownloadFormat();
        FileSystemResource resource;
        ZipEntry zipEntry;
        File dir;

        for (String dirStr:downloadFormat.split("-")) {
            dir = new File(System.getProperty("user.dir")+configProp.getProperty("output.dir")+dirStr);
            for (File file:dir.listFiles()) {
                resource = new FileSystemResource(System.getProperty("user.dir")+configProp.getProperty("output.dir")+dirStr+"/"+file.getName());

                zipEntry = new ZipEntry(file.getName());
                // Configure the zip entry, the properties of the file
                zipEntry.setSize(resource.contentLength());
                zipEntry.setTime(System.currentTimeMillis());
                // etc.
                zippedOut.putNextEntry(zipEntry);
                // And the content of the resource:
                StreamUtils.copy(resource.getInputStream(), zippedOut);
                zippedOut.closeEntry();
            }
        }
        zippedOut.finish();
    }


    public static void main(String[] args) throws IOException {

        // used to test runBusinessLogic() method

    }

}

这里是一个示例服务类,其中@Service似乎很重要

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private MyUserRepository repo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser user = repo.findByUsername(username);
        if(user==null)
            throw new UsernameNotFoundException("Username not found");

        return new UserPrincipal(user);
    }

    public MyUser getUser(String username) throws UsernameNotFoundException {
        MyUser user = repo.findByUsername(username);
        if(user==null)
            throw new UsernameNotFoundException("Username not found");

        return user;
    }

    public MyUser createUser(MyUser user) {
        String email = user.getEmail();
        String username = user.getUsername();
        if(repo.existsUserByEmail(email)) {
            user = repo.findByEmail(email);
        } else  if(repo.existsUserByUsername(username)) {
            user = repo.findByUsername(username);
        } else {
            this.repo.save(user);
            user = repo.findByEmail(email);
        }
        return user;
    }
}
    

我知道@Service是@Component的一种,就像@Controller和@Repository一样。我也了解这些类型级别(类级别)的构造型可以帮助组件扫描获取不同的...

spring spring-boot annotations spring-annotations
1个回答
0
投票

如果Java类用@Service注释,Spring将对其进行管理,并且可以享受Spring提供的好处,例如应用一些AOP魔术(例如@Transactional@Async@PreAuthorize等东西。 )。另外,其他实例也可以使用@Autowired而不是DIY来访问它(即依赖项注入方法)。考虑一下,如果您的对象由许多依赖关系组成,而这些依赖关系又由许多依赖关系组成,那么手动配置该实例以使其具有正确的依赖关系图可能不是一件令人愉快的事情。更不用说依赖对象应该来自正确的范围。

© www.soinside.com 2019 - 2024. All rights reserved.