Skip to content

Instantly share code, notes, and snippets.

@ochinchina
Last active December 14, 2015 09:58
Show Gist options
  • Select an option

  • Save ochinchina/7eec0f4b66e9ad8f1322 to your computer and use it in GitHub Desktop.

Select an option

Save ochinchina/7eec0f4b66e9ad8f1322 to your computer and use it in GitHub Desktop.
spring: autowire bean to non-managed object
package org.spring.test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
@Configuration
@EnableSpringConfigured
@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
public class AppConfig {
@Bean
@Lazy
public EchoService echoService(){
return new EchoService();
}
}
aspectjrt-1.8.7.jar
aspectjweaver-1.8.7.jar
commons-logging-1.2.jar
spring-aop-4.2.2.RELEASE.jar
spring-aspects-4.2.2.RELEASE.jar
spring-beans-4.2.2.RELEASE.jar
spring-context-4.2.2.RELEASE.jar
spring-core-4.2.2.RELEASE.jar
spring-expression-4.2.2.RELEASE.jar
spring-instrument-4.2.2.RELEASE.jar
spring-instrument-tomcat-4.2.2.RELEASE.jar
package org.spring.test;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
@Configurable( preConstruction = true, autowire = Autowire.BY_TYPE, dependencyCheck = false )
public class EchoDelegateService {
@Autowired
private EchoService echoService;
public void echo( String s ) {
echoService.echo( s );
}
}
package org.spring.test;
import org.springframework.stereotype.Service;
@Service
public class EchoService {
public void echo( String s ) {
System.out.println( s );
}
}
package org.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class);
new EchoDelegateService().echo("hihi, it works...");
}
}
run the application with following command:
```shell
$ java -cp lib/* -javaagent:lib/spring-instrument-4.2.2.RELEASE.jar org.spring.test.MainApp
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment