Skip to content

Add support for @javax.annotation.Priority as alternative to @Primary [SPR-10548] #15179

Closed

Description

@spring-projects-issues

Nick Williams opened SPR-10548 and commented

If multiple beans are candidates to satisfy an @Autowired/@Inject dependency, Spring looks for the @Primary annotation on one of the beans. If it finds it, it uses that bean; otherwise, it throws an exception.

javax.annotation version 1.2 (Java EE 7 and in theory Java 8) adds a new annotation to the common annotations, @Priority.

@Priority includes a single integer attribute that defines what the priority is. My suggestion is that if multiple beans are candidates to satisfy an @Autowired/@Inject dependency and @Primary is not present, Spring should look for @Priority instead. If one or more of the beans have @Priority, the one with the highest priority should be used. If two or more beans are tied for highest priority, it should behave the same as if two or more beans were @Primary.

Thoughts?


Affects: 4.0 M1

Issue Links:

1 votes, 7 watchers

Activity

  1. spring-projects-issues commented on Jul 2, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Phil Webb commented

    @javax.annotation.Priority looks a lot like @org.springframework.core.annotation.Order at first glance. Do have a specific use-case where this kind of support would be useful?

  2. spring-projects-issues commented on Dec 26, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Martin Frey commented

    I did a similar extension in a spring mvc application.

    First i used @ordered but came finally up with a @precedence annotation.
    I felt better with Precedence as i have implemented some predefined constants for it like FRAMEWORK, APPLICATION and MOCK.

    I used it to implement two scenarios:
    1: testing: having MOCK precedence easily allowed us unit and integration testing with adding the desired class in the scanned path to superseed beans without additional configuration. Mailsender for example.

    2: default behaviors which can be changed for client needs by simply adding the desired (custom) package for the client, if the default behavior was not enough. One example here would be our standard transition configuration for an entity which basically maps CRUD. Some need just that, other transition flows need to have a more sofisticated "workflow" with additional stati like ARCHIVED, DRAFT, etc.

    Having this precedence implementation in the BeanFactory's determinePrimaryCandidate method allowed us simple configuration by adding classes.

    The initial idea comes from JBoss Seam which had this exact behaviour.

    I should be able to provide you with my implemetation of that feature for spring 3.2 later ones i have access to my machine.

  3. spring-projects-issues commented on Dec 30, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Martin Frey commented

    Here's the code I'm currently using in a 3.2 Spring MVC project:

    public class ExtendedBeanFactory extends DefaultListableBeanFactory {
    	@Override
    	protected String determinePrimaryCandidate(Map<String, Object> candidateBeans, DependencyDescriptor descriptor) {
    		if (log.isDebugEnabled()) {
    			log.debug("Checking primary candidate based on Precedence for {}.{}", descriptor.getField().getDeclaringClass(), //$NON-NLS-1$
    					descriptor.getDependencyName());
    		}
    		List<CandidateBean> candidates = new ArrayList<>();
    		for (Entry<String, Object> candidate : candidateBeans.entrySet()) {
    			candidates.add(new CandidateBean(candidate.getKey(), candidate.getValue()));
    		}
    		Collections.sort(candidates);
    		CandidateBean c1 = candidates.get(0);
    		CandidateBean c2 = candidates.get(1);
    		if (c1.getPrecedence() > c2.getPrecedence()) {
    			if (log.isDebugEnabled()) {
    				log.debug("Found single candidate with highest Precedence {}.{} = {}", descriptor.getField() //$NON-NLS-1$
    						.getDeclaringClass(), descriptor.getDependencyName(), c1.getBeanName());
    			}
    			return c1.getBeanName();
    		} else {
    			log.debug("No precedence differences. Using original implementation"); //$NON-NLS-1$
    		}
    		return super.determinePrimaryCandidate(candidateBeans, descriptor);
    	}
    
    }
    public class CandidateBean implements Comparable<CandidateBean> {
    	private final String beanName;
    	private final Object candiate;
    	private final int precedence;
    
    	public CandidateBean(String beanName, Object candidate) {
    		this.beanName = beanName;
    		this.candiate = candidate;
    		if (candidate.getClass().isAnnotationPresent(Precedence.class)) {
    			this.precedence = candidate.getClass().getAnnotation(Precedence.class).value();
    		} else {
    			this.precedence = Precedence.APPLICATION;
    		}
    	}
    
    	@Override
    	public int compareTo(CandidateBean o) {
    		return o.getPrecedence() - this.getPrecedence();
    	}
    }
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface Precedence {
    	public static final int APPLICATION = 0;
    	public static final int FRAMEWORK = 1000;
    	public static final int MOCK = -1000;
    
    	int value() default APPLICATION;
    
    }
  4. spring-projects-issues commented on Jan 13, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    Nick, is there any reason why you mentioned @Order? AFAIK, order is not used at all. Mixing @Priority with @Order might not be such a good idea as @Order can already be set on existing beans for other purposes.

    I recommend therefore to only implement a support for @Priority as you mentioned in your original description and leave @Order for other use cases.

  5. spring-projects-issues commented on Jan 13, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Nick Williams commented

    No, I never suggested that it's wise to mix any two or three of @Priority, @Primary, or @Order. It's not. My suggestion is: Where Spring currently supports @Primary, it should support @Priority as an alternative to @Primary; and where Spring currently supports @Order, it should support @Priority as an alternative to @Order.

  6. spring-projects-issues commented on Jan 13, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    OK. Could you please raise a separate issue for the @Priority alternative for @Order? This is really a completely different request and it would be better to track those separately.

    Thanks!

  7. spring-projects-issues commented on Jan 17, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    See PR #442

  8. spring-projects-issues commented on Mar 31, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    This is now available in master and in the next 4.1.0.BUILD-SNAPSHOT.

    When multiple candidates are available for a given bean, the bean annotated with @Primary is used. If none exists, the one with the higher value for the @Priority annotation is used. If two beans have the same priority a NoUniqueBeanDefinitionException is thrown, just as if two beans are annotated with @Primary.

  9. spring-projects-issues commented on Mar 31, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    Do we actually have a follow-up issue here for supporting @Priority as an alternative to @Order? It'd be an interesting variation, since @Primary and @Order are basically independent characteristics at this point (for injection purposes), whereas @Priority would then be indicative for both purposes...

    Juergen

  10. spring-projects-issues commented on Mar 31, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    Right, #16262 has been created for that. Thanks for the reminder Jürgen.

  11. spring-projects-issues commented on Jul 7, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Martin Frey commented

    I'd like to reopen this issue as I think this needs alignment with the current @Order implementation:

    Is it intended that this implementation works inverse to the @Order implementation?

    @Priority -> Highest Priority = MAX_INTEGER

    @Order -> Highest Priority = MIN_INTEGER

    I would say this should be aligned.

    Else great job.

  12. spring-projects-issues commented on Jul 7, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    Hi Martin,

    I am not sure I understand what you mean there. There is no "common" behaviour for the standard annotation

    The effect of using the Priority annotation in any particular instance is defined by other specifications that define the use of a specific class.

    The current code makes sure that the lowest value has the highest priority (to align with what @Order provides). Do you mean you'd like to reverse that? On what ground? Thanks!

  13. spring-projects-issues commented on Jul 7, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Phil Webb commented

    Martin Frey I have a feeling that the semantics of the value field intentionally differ from @Order. Looking at the javadoc for @Priority it appears that negative numbers at least should not be used (https://javaee-spec.java.net/nonav/javadocs/javax/annotation/Priority.html)

  14. spring-projects-issues commented on Jul 7, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Martin Frey commented

    I just tried v4.1 today and removed my originally superseding version of the bean factory.

    For me it was strange to see that an @Order ed list results in the lowest number being the first element and an auto wired single field resulted in the wiring of the last element of that list as the @Primary.

    Basically my test included defining an interface with two implementations. One without priority and one with a "high" priority according to the @Order behavior.

    The expected result was that the ordered list first element is the same as the resulting primary.

    This was not true using the snapshot of today. The current determineHighestPriorityCandidate implementation uses the highest integer value found, while the AnnotationAwareOrderComparator does the inverse.

    This would mean that to make sure that the ordered list first element and the primary object matches, the class would need to define both annotations @Order and @Priority with the "exact" inverted integer to achieve the expected behavior.

        class OrderingTest {
        
            @Autowired
            private List<SomeInterface> someInterfaces;
    
            @Autowired
            private SomeInterface primaryInterface;
    
            public void test() {
                Assert.assertEquals(2, someInterfaces);
    
                Assert.assertEquals(HighestInterface.class, someInterfaces.get(0).getClass());
                Assert.assertEquals(DefaultInterface.class, someInterfaces.get(1).getClass());
    
                // these fail
                Assert.assertEquals(HighestInterface.class, primaryInterface.getClass());
                // first element of ordered list should be the primary
                Assert.assertEquals(someInterfaces.get(0).getClass(), primaryInterface.getClass());
        }

    EDIT: Here's the "offending" code: DefaultListableBeanFactory.java Line 1161:

    else if (candidatePriority > highestPriority) {
        highestPriorityBeanName = candidateBeanName;
        highestPriority = candidatePriority;
    }
  15. spring-projects-issues commented on Jul 7, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    Martin, thank you so much for testing this. You are right, I got confused (again!) with the semantic of order (highest precedence means low value). My brain does not want to accommodate with it ;)

    It also turns out we may be missing one test here that validates the Primary/Priority and collection ordering. I'll work on that and let you know when I am done.

    Thanks again!

  16. spring-projects-issues commented on Jul 8, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    The semantic inconsistency has been fixed. A new 4.1.0.BUILD-SNAPSHOT will be available soon. Please give it a try if you can.

    Thanks!

  17. spring-projects-issues commented on Jul 8, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Martin Frey commented

    Nice work. It's working fine now :) Thanks a lot.

    (By the way: Looks like my supported applications run in 4.1 without a problem until now.)

  18. added
    type: enhancement
    in: core
    on Jan 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

in: coretype: enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions