Announcement Announcement Module
Collapse
No announcement yet.
@Autowired issues when running junits. Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • @Autowired issues when running junits.

    Hey guys, I have configured a bean in my xml (and I see it getting instantiated on load)

    Code:
    <bean id="cache" class="my.correct.path.CacheImpl" autowire-candidate="true" autowire="byName" name="cache">
    		<constructor-arg>
    			<util:properties id="properties" location="classpath:META-INF/spring/cache/cache.properties" />
    		</constructor-arg>
    	</bean>
    I've created a common Cache interface for different caching systems, it implements this:

    Code:
    @Component
    public interface Cache<T> {
    	public Map<Object, T> getRegion(CacheEnum e);
    	public T get(Object key, CacheEnum c);
    	public void put(Object key, T value, CacheEnum c);
    }
    I want to autowire it into the project so I try to do this:

    Code:
    @Component
    public class TypedCacheImpl<T> implements Serializable {
    
    	private static final long serialVersionUID = -6094798210446446133L;
    
    	@Autowired
    	private Cache<T> cache;
    
    	private Repository repo;
    	
    	@Autowired
    	public TypedCacheImpl(Repository repo) {
    		this.repo = repo;
    	}
    	
    	@Autowired
    	public TypedCacheImpl(Repository repo, Cache<T> cache) {
    		this.repo = repo;
    		this.cache = cache;
    	}
    	
    	public T findById(String id) {
    		T cachedObj = getCache().get(id, CacheEnum.Region);//NPE, getCache is null
    		if (cachedObj == null){
    			cachedObj = repo.findById(id);
    			if(cachedObj != null)getCache().put(id, cachedObj, CacheEnum.Region);
    		}
    		return cachedObj;
    	}
    	
    	public void setCache(Cache<T> cache){
    		this.cache= cache;
    	}
    	
    	public Cache<T> getCache(){
    		return cache;
    	}
    
    }

    CacheImpl.java
    Code:
    @Component
    public class CacheImpl<T> extends CacheFactory implements Cache<T>, Serializable  {
        ...
    }
    I also have the context scan on both CacheImpl and Cache object. (Local implementations) so my question is: Why isn't autowire working in the first place and how do I autowire the specific CacheImpl when I do @Autowired Cache<T> cache; ? I don't want to do Cache cache = (Cache) ApplicationContext.getBean("cache");

    Thanks!

  • #2
    For starters you have 2 instances of your cache, @Autowired will only work with a single instance (or you need to specify the name with @Qualifier). You have 2 instances because you define 1 instance in your xml and the other one is detected using component scanning.

    Comment

    Working...
    X