Spring AOP - Setting Advice on a POJO getter - advice is not called - spring

I'm pretty new to Spring and I'd like to use Spring AOP to be able to fire an advice when a POJO getter is being called.
I created a simple POJO:
package com.atlas.datastore.datadomain;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.stereotype.Component;
#Component
public class Person
{
private String name;
public String getName() {
System.out.println(name);
return name;
}
public void setName(String name) {
this.name = name;
}
}
And I created an Aspect for the name getter:
package com.atlas.datastore.aspects;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
#Component
#Aspect
public class personAspect {
#Pointcut("execution(* com.atlas.datastore.datadomain.Person.getName())")
private void getName() {}
#Before("getName()")
public void doBeforeTask(){
System.out.println("My name is: " );
}
}
I created a controller (spring boot simple application) to use the getter:
package com.example.Controller;
import com.atlas.datastore.datadomain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/person")
public class PersonController {
#Autowired
private Person person;
#RequestMapping(value = "/{personId}", method = RequestMethod.GET)
#ResponseBody()
public Person personAction(#PathVariable String personId) {
person.setName("John");
person.getName();
return person;
}
}
When I run the application everything works fine and I can see that the advice is being fired.
The problem I have is that I do not want to auto-wire the Person object. When I create a Person with a default constructor (using new keyword), I see that the advice is not being fired:
package com.example.Controller;
import com.atlas.datastore.datadomain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/person")
public class PersonController {
#RequestMapping(value = "/{personId}", method = RequestMethod.GET)
#ResponseBody()
public Person personAction(#PathVariable String personId) {
Person person = new Person();
person.setName("John");
person.getName();
return person;
}
}
In my configuration I am using the following annotation:
#EnableAspectJAutoProxy(proxyTargetClass = true)
I can see the following output in the log:
18:12:40.152 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'person'
18:12:40.152 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'person'
18:12:40.152 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'person' to allow for resolving potential circular references
18:12:40.153 [main] DEBUG o.s.a.a.a.AnnotationAwareAspectJAutoProxyCreator - Creating implicit proxy for bean 'person' with 0 common interceptors and 2 specific interceptors
18:12:40.153 [main] DEBUG o.s.aop.framework.CglibAopProxy - Creating CGLIB proxy: target source is SingletonTargetSource for target object [com.atlas.datastore.datadomain.Person#7de4a01f]
18:12:40.154 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'person'
I'd appreciate your help

Using the new operator to directly create an instance like Person person = new Person() bypasses the Spring and so Spring doesn't get a chance to inject the dependencies in this object or proxy this object.
To make Spring inject the dependencies or proxy for above scenarios where new operator is used, we need to Annotate the Person object as #Configurable, configure AnnotationBeanConfigurerAspect, use Spring LoadTimeWeaving and run the application with -javaagent .....
You can find sample usage of this at https://dzone.com/articles/domain-object-dependency-injection-with-spring

Instead of adding the #Pointcut to a domain object:
com.atlas.datastore.datadomain.Person.getName()
consider creating a service instead which takes a Person object as a parameter. Add the #Pointcut to the service method.
Inject the service into your web controller, and then call the service passing the 'new' Person.

Related

How to implement multiton pattern using Spring Framework

How does one implement multiton pattern using Spring Framework's facilities?
https://en.wikipedia.org/wiki/Multiton_pattern
I want to write a factory which takes a pair of client and supplier as arguments. The factory should always return a bean of type T. For a given pair of client and supplier, the instance of T return should be a singleton, but for a different pair of client and supplier, it will be a different instance of T. Please suggest a way to implement this without implementing boilerplate code that Spring may already provide.
Interface ClientSdk {
sendRequestToClient();
}
class ClientASdk implements ClientSdk {
}
class ClientBSdk implements ClientSdk {
}
enum Client {
ClientA,
ClientB;
}
enum Supplier {
SupplierA,
SupplierB;
}
class ClientSupplier {
private Client client;
private Supplier supplier;
}
class SdkFactory {
public ClientSdk getClientSdk(ClientSupplier clientSupplier) {
//For a given ClientSupplier, always return the same
//ClientSupplier instance
}
}
#Service
class ClientRequestService {
public sendRequestToClient(ClientSupplier clientSupplier) {
ClientSdk clientSdk = SdkFactory.getSdk(clientSupplier);
clientSdk.sendRequestToClient();
}
}
Here's a solution to your problem. It does make SdkFactory a bean as #crizzis suggests, but it also creates bean instances for each ClientSdk instance so that each of them can be autowired or otherwise helped out by Spring. Note that I added an ident() method to the ClientSdk interface just to show that the MyClientSdk beans have in fact been autowired with the Spring Environment:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
interface ClientSdk {
void sendRequestToClient();
}
// This class is instantiated via a #Bean method inside SdkFactory. Since it is annotated as a Prototype bean,
// multiple instances of this class can be created as beans.
class MyClientSdk implements ClientSdk {
#Autowired
Environment environment;
private final String clientSupplier;
MyClientSdk(String clientSupplier) {
this.clientSupplier = clientSupplier;
System.out.printf("### Created MyClientSdk for: %s\n", clientSupplier);
}
public void sendRequestToClient() {
System.out.printf("Sending request for client: %s\n", clientSupplier);
System.out.printf("CS: %s Environment Prop: %s\n", clientSupplier, environment.getProperty("spring.application.name"));
}
}
#Component
class SdkFactory implements BeanFactoryAware {
private Map<String, ClientSdk> sdks = new HashMap<>();
private BeanFactory beanFactory;
// Here's the key logic to insure that we get just one instance of ClientSdk per clientSupplier value.
ClientSdk getClientSdk(String clientSupplier) {
if (!sdks.containsKey(clientSupplier))
sdks.put(clientSupplier, beanFactory.getBean(ClientSdk.class, clientSupplier));
return sdks.get(clientSupplier);
}
// This is probably the most important bit. This creates a Spring Bean unique to a particular 'clientSupplier'
// value, but only does so when requested so that the factory can control when these beans are created, creating
// only one per a particular `clientSupplier` value.
#Bean
#Scope("prototype")
ClientSdk createSdk(String clientSupplier) {
return new MyClientSdk(clientSupplier);
}
#Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
#Service
class ClientRequestService {
#Autowired
SdkFactory factory;
public void sendRequestToClient(String clientSupplier) {
ClientSdk clientSdk = factory.getClientSdk(clientSupplier);
clientSdk.sendRequestToClient();
}
}
#SpringBootApplication
public class HarmonyTestApp implements CommandLineRunner {
#Autowired
ClientRequestService service;
public static void main(String[] args) {
try {
ApplicationContext applicationContext = new SpringApplication(new Class<?>[]{HarmonyTestApp.class}).run(args);
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void run(String... args) {
service.sendRequestToClient("client1");
service.sendRequestToClient("client2");
service.sendRequestToClient("client1");
service.sendRequestToClient("client1");
service.sendRequestToClient("client2");
}
}
Result:
### Created MyClientSdk for: client1
Sending request for client: client1
CS: client1 Environment Prop: TestApp
### Created MyClientSdk for: client2
Sending request for client: client2
CS: client2 Environment Prop: TestApp
Sending request for client: client1
CS: client1 Environment Prop: TestApp
Sending request for client: client1
CS: client1 Environment Prop: TestApp
Sending request for client: client2
CS: client2 Environment Prop: TestApp
Note that per the output, each of client1's and client2's ClientSdk objects are only created once, even though they're used multiple times. Also notice that since the call to ident() in sendRequestToClient prints the value of a property obtained by an autowired Environment instance, autowiring of each ClientSdk object has worked.
I do realize that I used a String instead of a ClientSupplier object as the identifying key for each ClientSdk object. I did that just to keep the example as simple as I could. I expect you can expand the example to replace the clientSupplier String with an instance of ClientSupplier and somehow use that object as the key/identifier to insure that just one ClientSdk instance is created per ClientSupplier. That detail isn't really germain to the basic idea here.
Also, please note that the question itself changed while I was working on my implementation. Given that there are now exactly two subclasses of ClientSdk, you could simply make those regular #Component Spring beans. Having a small static number of those makes this problem less interesting. The technique I demonstrate here allows for an unlimited number of bean instances of ClientSdk class without having to define a unique class for each of them. This requires that Spring create arbitrary instances of them based on runtime information. This was what the original form of the question seemed to be asking for.

Jersey and EJB stateless example, EJB instance is null

I am making a simple RESTful service using JAVAX RS and EJB in order to create a singleton object as a global variable.
I initiated the service as follows:
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
final ResourceConfig rc = new ResourceConfig().packages("service_folder");
GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
I am currently just testing the #Stateless example.
Firstly, I create a class in a random folder, and the content as follows:
import javax.ejb.Stateless;
import java.util.Date;
#Stateless
public class Service {
public Date getCurrentDate(){
return new Date();
}
}
Then I create the resource file in the service_folder mentioned in the very beginning:
#Stateless
#Path("current")
public class ServiceFacade {
#EJB
Service service;
#GET
public String getDate(){
return service.getCurrentDate().toString();
}
}
The current situation is that whenever I access BASE_URI/current, grizzly simply throw an error, and the reason is because service in getDate() is null.
My guess is that during the grizzly init., the Service class bean isn't really registered yet.
Please let me know where did I do wrong, thanks!

NullPointer Exception everytime I try to run my Junit Test Case

Every time i try to run the junit test case , i get null pointer exception and also when i tried to hadle the exception everytime the function returns NULL value. Here is the code.
RestaurantRepository.java
package org.springsource.restbucks;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
#Component
#Transactional
public interface RestaurantRepository extends PagingAndSortingRepository<Restaurant, Long> {
#Query("SELECT p FROM Restaurant p Where (p.id)=(:Id) and p.deleted=false")
Restaurant findById(#Param("Id") long Id);
#Query("SELECT p FROM Restaurant p Where LOWER(p.name)=LOWER(:name) and p.deleted = false")
Restaurant findByName(#Param("name") String name);
}
RestaurantController.java
#RestController
public class RestaurantController {
#Autowired
RestaurantRepository repository;
#RequestMapping(value = "/restaurants/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public ResponseEntity<Restaurant> getRestaurant(#PathVariable("id") long restaurantId) {
Restaurant responseRestaurant = repository.findOne(restaurantId);
if(responseRestaurant==null){
logger.error("No Restaurant found with id:"+restaurantId);
return new ResponseEntity<Restaurant>(HttpStatus.NOT_FOUND);
}else if(responseRestaurant.isDeleted()==true){
logger.error("Restaurant Object is deleted");
return new ResponseEntity<Restaurant>(HttpStatus.NOT_FOUND);
}else{
return new ResponseEntity<Restaurant>(responseRestaurant,HttpStatus.OK);
}
}
}
RestaurantRepositoryTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class RestaurantRepositoryTest{
#Autowired
private RestaurantRepository repository;
#Test
public void testfindById() throws Exception{ //testing findbyid method in restaurant repository
Restaurant responseRestaurant = repository.findByName("xyz"); //getting error over here
assertEquals("xyz",responseRestaurant.getName());
}
}
I am getting null pointer exception whenever i run mvn test . the stack trace is below what i get displayed in terminal.
testfindById(org.springsource.restbucks.RestaurantRepositoryTest)
Time elapsed: 0.018 sec <<< ERROR! java.lang.NullPointerException:
null at
org.springsource.restbucks.RestaurantRepositoryTest.testfindById(RestaurantRepositoryTest.java:19)
what shall i do to run my test successfully??
You're running that as a pure unit test with no Spring context. Therefore, the repository will not be autowired. You should be able to fix that by adding a few annotations to the top of your test class.
If using Spring Boot, then something like the following should work, to let Spring Boot do all the hard work:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = MyApplication.class)
You can alternatively load the Spring #Configuration class which would initialise your repositories (In my case, this is called DbConfig), like so:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { DbConfig.class },
loader = AnnotationConfigContextLoader.class)
Your test is not starting up a Spring context at all, so the annotations are completely ignored. The best solution is to modify your controller class to take the repository as a constructor argument instead of using field injection. This allows you to pass in a simple mock, such as a Mockito mock, and avoid the complexity of starting up a Spring context to run a unit test.

How can I find all beans with the custom annotation #Foo?

I have this spring configuration:
#Lazy
#Configuration
public class MyAppConfig {
#Foo #Bean
public IFooService service1() { return new SpecialFooServiceImpl(); }
}
How can I get a list of all beans that are annotated with #Foo?
Note: #Foo is a custom annotation defined by me. It's not one of the "official" Spring annotations.
[EDIT] Following the suggestions of Avinash T., I wrote this test case:
import static org.junit.Assert.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.reflect.Method;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
public class CustomAnnotationsTest {
#Test
public void testFindByAnnotation() throws Exception {
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext( CustomAnnotationsSpringCfg.class );
Method m = CustomAnnotationsSpringCfg.class.getMethod( "a" );
assertNotNull( m );
assertNotNull( m.getAnnotation( Foo.class ) );
BeanDefinition bdf = appContext.getBeanFactory().getBeanDefinition( "a" );
// Is there a way to list all annotations of bdf?
Map<String, Object> beans = appContext.getBeansWithAnnotation( Foo.class );
assertEquals( "[a]", beans.keySet().toString() );
}
#Retention( RetentionPolicy.RUNTIME )
#Target( ElementType.METHOD )
public static #interface Foo {
}
public static class Named {
private final String name;
public Named( String name ) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
#Lazy
#Configuration
public static class CustomAnnotationsSpringCfg {
#Foo #Bean public Named a() { return new Named( "a" ); }
#Bean public Named b() { return new Named( "b" ); }
}
}
but it fails with org.junit.ComparisonFailure: expected:<[[a]]> but was:<[[]]>. Why?
Use getBeansWithAnnotation() method to get beans with annotation.
Map<String,Object> beans = applicationContext.getBeansWithAnnotation(Foo.class);
Here is similar discussion.
UPDATE: Spring 5.2 changed the behavior of context.getBeansWithAnnotation(...) and it now correctly handles beans created via factory methods. So simply use that.
Original answer
While the accepted answer and Grzegorz's answer contain approaches that will work in all cases, I found a much much simpler one that worked equally well for the most common cases.
Meta-annotate #Foo with #Qualifier:
#Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Qualifier
public #interface Foo {
}
Sprinkle #Foo onto the factory methods, as described in the question:
#Foo
#Bean
public IFooService service1() {
return new SpecialFooServiceImpl();
}
But it will also work on the type level:
#Foo
#Component
public class EvenMoreSpecialFooServiceImpl { ... }
Then, inject all the instances qualified by #Foo, regardless of their type and creation method:
#Autowired
#Foo
List<Object> fooBeans;
fooBeans will then contain all the instances produced by a #Foo-annotated method (as required in the question), or created from a discovered #Foo annotated class.
The list can additionally be filtered by type if needed:
#Autowired
#Foo
List<SpecialFooServiceImpl> fooBeans;
The good part is that it will not interfere with any other #Qualifier (meta)annotations on the methods, nor #Component and others on the type level. Nor does it enforce any particular name or type on the target beans.
With the help of a couple of Spring experts, I found a solution: The source property of a BeanDefinition can be AnnotatedTypeMetadata. This interface has a method getAnnotationAttributes() which I can use to get the annotations of a bean method:
public List<String> getBeansWithAnnotation( Class<? extends Annotation> type, Predicate<Map<String, Object>> attributeFilter ) {
List<String> result = Lists.newArrayList();
ConfigurableListableBeanFactory factory = applicationContext.getBeanFactory();
for( String name : factory.getBeanDefinitionNames() ) {
BeanDefinition bd = factory.getBeanDefinition( name );
if( bd.getSource() instanceof AnnotatedTypeMetadata ) {
AnnotatedTypeMetadata metadata = (AnnotatedTypeMetadata) bd.getSource();
Map<String, Object> attributes = metadata.getAnnotationAttributes( type.getName() );
if( null == attributes ) {
continue;
}
if( attributeFilter.apply( attributes ) ) {
result.add( name );
}
}
}
return result;
}
gist with full code of helper class and test case
Short story
It is not enough to put #Foo on the a() method in order to make the a bean annotated with #Foo.
Long story
I didn't realize it before I started debugging Spring code, a breakpoint at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAnnotationOnBean(String, Class<A>) helped me understand it.
Of course, if you moved your annotation to the Named class:
#Foo
public static class Named {
...
and fixed some minor details of your test (annotation target, etc.) the test works.
After giving it a second thought, it's quite natural. When getBeansWithAnnotation() is called, the only information Spring has are the beans. And beans are objects, objects have classes. And Spring doesn't seem to need to store any additional information, incl. what was the factory method used to create the bean annotated with, etc.
EDIT There is an issue which requests to preserve annotations for #Bean methods: https://jira.springsource.org/browse/SPR-5611
It has been closed as "Won't fix" with the following workaround:
Employ a BeanPostProcessor
Use the beanName provided to the BPP methods to look up the associated BeanDefinition from the enclosing BeanFactory
Query that BeanDefinition for its factoryBeanName (the #Configuration bean) and factoryMethodName (the #Bean name)
use reflection to get hold of the Method the bean originated from
use reflection to interrogate any custom annotations from that method
To get all annotated beans:
context.getBeansWithAnnotation(Foo.class)
This returns a Map<String, Object> where the key is the bean name.
To get the annotation class:
context.findAnnotationOnBean(beanName, Foo.class);
This can be helpful when the annotation has values (#Foo(weight=100)).
This is how to get annotated beans.
#Autowired
private ApplicationContext ctx;
public void processAnnotation() {
// Getting annotated beans with names
Map<String, Object> allBeansWithNames = ctx.getBeansWithAnnotation(TestDetails.class);
//If you want the annotated data
allBeansWithNames.forEach((beanName, bean) -> {
TestDetails testDetails = (TestDetails) ctx.findAnnotationOnBean(beanName, TestDetails.class);
LOGGER.info("testDetails: {}", testDetails);
});
}
In my case getBeansWithAnnotation was returning an empty list. My mistake was to not adding retention and target on my custom annotation.
Adding these lines no top of my annotation fixed it.
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)

Spring annotations - #Configuration to invoke spring bean auto-building

If I declare a class using #Bean and then component scan for the class, spring will instantiate the class by invoking it's constructor and injecting constructor args and injecting any fields marked with #Inject. For simplicity's sake, lets call this spring auto-building.
I dislike component scan and wish to avoid it completely (I don't wish to discuss my reasons for not liking it). I would like to use a #Configuration object instead but would still like to have the auto-building functionality available to me. Is it possible to invoke spring to auto-build my objects instead of explicitly having to pass all the constructor arguments in my #Configuration object?
Lets assume that I have a bean:
public class MyServiceImpl implements MyService {
public MyServiceImpl(Dependency1 d1, Dependency d2) { ... }
....
}
I could define a configuration object like this:
#Configuration
public class MyConfiguration {
// lets assume d1 and d2 are defined in another #Configuration
#Inject
Dependency1 d1;
#Inject
Dependency2 d2;
#Bean
public MyService myService() {
// I dislike how I have to explicitly call the constructor here
return new MyServiceImpl(d1, d2);
}
}
But now, I have explicitly had to call the MyServiceImpl constructor myself so I will have to keep updating this as my constructor changes over time.
I was hoping that I could declare an abstract method so that spring auto-building could take place:
#Configuration
public abstract class MyConfiguration {
#Bean
public abstract MyServiceImpl myService();
}
But this doesn't work. Is there a way that I can invoke spring auto-building without using a component scan?
In Google Guice, this can be done via the Binder:
https://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Binder.html
In Tapestry IOC, this can be done via the ServiceBinder:
http://tapestry.apache.org/ioc-cookbook-basic-services-and-injection.html#IoCCookbook-BasicServicesandInjection-SimpleServices
Update
Based on spod's answer, I was able to achieve what I was after (thanks!). Test case included for anyone that wants to do the same:
import java.util.Date;
import javax.inject.Inject;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class AutoBuildConfigurationTest {
#Configuration
public static class MyConfiguration {
#Inject
private AutowireCapableBeanFactory beanFactory;
#Bean
public Date date() {
return new Date(12345);
}
#Bean
public MyService myService() {
return autoBuild(MyService.class);
}
protected <T> T autoBuild(Class<T> type) {
return type.cast(beanFactory.createBean(type, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true));
}
}
public static class MyService {
private Date date;
public MyService(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
}
#Test
public void testAutoBuild() {
ApplicationContext appContext = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyService myService = appContext.getBean(MyService.class);
Assert.assertEquals(12345, myService.getDate().getTime());
}
}
The java based container configuration doesnt depend on doing a component scan in any way. Its merely a different approach for the XML based component configuration. With the XML configuration you'd just have to declare your bean with the MyServiceImpl class in case its already #inject annotated. Spring would recognize the annotations and take care of them. If you really want to instanciate MyServiceImpl from a #Configuration java class without calling the constructor yourself, then you'd have to make use of the bean factory (havent tested it, just give it a try):
#Configuration
public class MyConfiguration {
#Autowired AutowireCapableBeanFactory beanFactory;
#Bean public MyService myService() {
return beanFactory.createBean(MyServiceImpl.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true);
}
}

Resources