SpringUtil tool class - static method to get Bean

When you need to directly call the static method in the class: class name. method name () when calling directly

However, some SpringBoot non-static variables or injected beans cannot be obtained in static methods, and it is troublesome to change them

@Value("${company.file.upload}")
private String upload;
 
@Resource
private AttachmentService attachmentService;

Then you can use  the SpringUtil.getBean()  method at this time, and you can add a public static void fileConverter  method to provide calls , and the original method does not need to be changed .

@Component("libreOfficeUtils")
public class LibreOfficeUtils {
 
    @Value("${company.file.upload}")
    private String upload;
 
    @Resource
    private AttachmentService attachmentService;
 
    private static final Logger log= LoggerFactory.getLogger(LibreOfficeUtils.class);
 
    /**
     * 文档转换
     * @param newAttachmentId 附件id
     * @throws Exception
     */
    public static void fileConverter(Long newAttachmentId) {
        LibreOfficeUtils libreOfficeUtils = SpringUtil.getBean("libreOfficeUtils");
        libreOfficeUtils.fileConverter2(newAttachmentId);
    }
    /**
     * 文档转换
     * @param newAttachmentId 附件id
     * @throws Exception
     */
    public void fileConverter2(Long newAttachmentId) {
        // 需要用到upload,attachmentService的业务...
    }
 
}

by the way: The purpose of the static keyword
  There is a passage on page P86 of "Java Programming Thoughts":

  "A static method is a method without this. You cannot call a non-static method inside a static method, and vice versa. And you can call a static method only through the class itself without creating any objects. This is actually The main purpose of the static method."

———————Because it is not attached to any object, since there is no object, there is no such thing as this

  Although this passage only explains the special features of the static method, we can see the basic function of the static keyword. In short, the description in one sentence is:

  It is convenient to call (method/variable) without creating an object.

  Obviously, the method or variable modified by the static keyword does not need to depend on the object to access, as long as the class is loaded, it can be accessed through the class name.

  static can be used to modify class member methods and class member variables. In addition, static code blocks can be written to optimize program performance. 

Guess you like

Origin blog.csdn.net/qq_39706515/article/details/130768356