Java Series - Dependency Injection and Related Issues

origin

Using the @Autowire annotation in Idea will prompt a yellow line, which makes it difficult for patients with obsessive-compulsive disorder.
It can be resolved after using constructor injection or setter method injection

Three Dependency Injection Methods in Spring

  • Field Injection : One of the usage scenarios of @Autowired annotation is Field Injection
  • Constructor Injection : Constructor injection is the most recommended way of use in our daily life
  • Setter Injection : Setter Injection also uses the @Autowired annotation, but it is used differently from Field Injection. Field Injection is used on member variables, while Setter Injection is used on the Setter function of member variables.
// Field Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {
    
    
    @Autowired
    private UploadDao uploadDao;

}
// Constructor Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {
    
    

    private UploadDao uploadDao;
	UploadServiceImpl(UploadDao uploadDao){
    
    
		this.uploadDao = uploadDao;
	}
}
// Setter Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {
    
    

    private UploadDao uploadDao;
    
	@Autowired
	public void setUploadDao(UploadDao uploadDao){
    
    
		this.uploadDao =uploadDao
	}
}

1. Whether to perform circular dependency detection

  • Field Injection: No detection
  • Constructor Injection: automatic detection
  • Setter Injection: No detection

possible problems

  1. Circular dependency error : When service A needs to use service B, and service B needs to use service A, when Spring initializes and creates beans, it does not know which one should be created first, and this error will appear.
This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example
class ServerA{
    
    
	@Autowired
	private ServerB b;
}

class ServerB{
    
    
	@Autowired
	private ServerA a;
}

If you use construction injection, it can accurately remind you which two classes have a circular dependency. The abnormal error message can quickly locate the problem:
insert image description here

The solution to circular error reporting is to use the @Lazy annotation to add this annotation to any bean that needs to be injected, indicating that the creation is delayed.

class ServerA{
    
    
	@Autowired
	@Lazy
	private ServerB b;
}

class ServerB{
    
    
	@Autowired
	@Lazy
	private ServerA a;
}

------ If the article is useful to you, thank you >>> Like | Favorites<<<

Guess you like

Origin blog.csdn.net/win7583362/article/details/124681712