@Primary use

A small discovery in making the wheel

When an interface is implemented by two services, the controller calls the interface implementation function, and an error will be reported, prompting the developer to specify the service. Officially, it is recommended that you use @Qualifier to distinguish, but there is always another way to achieve it.

 

Scenes

public interface Hi{ String hi(); }

@Service
public class Hi1 implements Hi{
    @Override
    public String hi() {
        return "hi1";
    }
}

@Service
public class Hi2 implements Hi{
    @Override
    public String hi() {
        return "hi2";
    }
}
@Controller
public class SingerService { @Autowired privateHi hi; public String sing(){ return hi.hi(); } } 
 

If no specific interface implementation class is specified at this time, spring will report an error, but as long as Hi2 is changed to

@Service
@Primary public class Hi2 implements Hi{ @Override public String hi() { return "hi2"; } }

 The command line will output

hi2

@Primary means the default, and his usage is of course not for the service layer, but when building a wheel, often a basic interface class has multiple implementations, we only need to add @Primary to one of the implementations, then There is no need to @Qualifier every time when using this interface class, and for most developers, just understanding and using the default functionality is enough.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326271981&siteId=291194637