I am trying to set up Spring AOP without any XML and wonder how to enable auto-proxying this way.
Defining an AutoProxyCreator-bean works, but isn't there an easier way?
This is what my #Configuration looks like:
#Configuration
public class Context {
#Bean
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
return new AnnotationAwareAspectJAutoProxyCreator();
};
...
}
All other beans are scanned in by AnnotationConfigApplicationContext.
Spring 3.0.x doesn't provide easy ways to replace XML namespace extensions (such as <aop:aspectj-autoproxy>) in #Configuration.
An upcoming Spring 3.1 will support special annotations for this purpose, such as #EnableAspectJAutoProxy.
Finally I found an aesthetically pleasing way to add the AnnotationAwareAspectJAutoProxyCreator:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AnnotationAwareAspectJAutoProxyCreator.class);
context.scan("com.myDomain");
context.refresh();
Related
I'm new in Spring applications, and see the big difference between configurations in springBoot and spring. So my questin is: apart from spring-boot, is there a way to setup a proper spring application(with web mvc, security, aop, ...), without any xml config file (ie : config relying only on annotations).
Yes, there is a way to do this in Spring. Spring Boot is after all an enhanced, autoconfigured Spring (with other cool features). That means that everything there is in Spring Boot should be achievable in Spring as well, but you would have do a bit/a lot of Your own extra work.
Moving straight to the point, in order to achieve what you want, you would need to undertake the following steps:
Create a class, which will store all the configuration (basically the properties you would store in the xml file) - let's call it AppConfig.class
Annotate the AppConfig.class with #Configuration - this will inform Spring that this class is the source of configuration;
Annotate the AppConfig.class with #ComponentScan("com.app") - here, You need to provide a package, from which Spring has to start component scanning in order to find Beans to be registered in Spring Container. Important note is, that it will scan the package and it's subpackages, so you would mostly want to provide here the top level package;
If you need some data to be injected into your beans, you would want to use the #PropertySource("classpath:application.properties") - I have provided here the default value, which Spring Boot uses internally in case you want to inject some data into your beans at runtime. For this to work, you need to inject into AppConfig.class an Environment.class
To show it on the example:
#Configuration
#ComponentScan("com.app")
#PropertySource("classpath:application.properties")
public class AppConfig {
// it will help to pull the properties incorporated in the file you have provided in the #PropertySource annotation
private Environment environment;
//inject it
public AppConfig(Environment environment) {
this.environment = environment;
}
// build your beans - the getProperty method accepts the key from application.properties
// file and return a value as a String. You can provide additional arguments to convert
//the value and a default value if the property is not found
#Bean
public Product product() {
return new Product(
environment.getProperty("product.name", "XXX"),
environment.getProperty("product.price", BigDecimal.class, BigDecimal.ZERO),
environment.getProperty("product.quantity", Integer.class, 10)
);
}
}
I hope that it helps
I am trying to learn to migrate one spring XML based application to spring boot application and wondering with one scenario where we have multiple constructors in a class and wish to inject all these using spring annotation.
I do understand and implemented the way using XML based configuration but confused with which annotation/way to inject multiple constructors.
I tried referring to few forums like : Ambiguity Regarding Spring Constructor Injection but no luck with spring boot.
Could anyone please help on this please?
As it was mentioned in comments you can use #Configuration
#Configuration
public class Config {
#Bean
public Employee employee() {
return new Employee(10,"100");
}
}
I'm getting back into Spring (currently v4). It's all wonderful now with #SpringBootApplication and the other annotations but all the documentation seems to forget to mention how I define other beans in XML!
For example I'd like to create an "SFTP Session Factory" as defined at:
http://docs.spring.io/spring-integration/reference/html/sftp.html
There is a nice bit of XML to define the bean but where on earth do I put it and how do I link it in? Previously I did a:
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
to specify the file name and location but now that I'm trying to use:
ApplicationContext ctx = SpringApplication.run(Application.class);
Where do I put the XML file? Is there a magic spring name to call it?
As long as you're starting with a base #Configuration class to begin with, which it maybe sounds like you are with #SpringBootApplication, you can use the #ImportResource annotation to include an XML configuration file as well.
#SpringBootApplication
#ImportResource("classpath:spring-sftp-config.xml")
public class SpringConfiguration {
//
}
You also can translate the XML config to a Java config. In your case it would look like:
#Bean
public DefaultSftpSessionFactory sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setHost("localhost");
factory.setPrivateKey(new ClassPathResource("classpath:META-INF/keys/sftpTest"));
factory.setPrivateKeyPassphrase("springIntegration");
factory.setPort(22);
factory.setUser("kermit");
return factory;
}
You can put this method in the class with the #SpringBootApplication annotation.
Spring boot ideal concept is avoid xml file. but if you want to keep xml bean, you can just add #ImportResource("classPath:beanFileName.xml").
I would recommend remove the spring-sftp-config.xml file. And, convert this file to spring annotation based bean. So, whatever class has been created as bean. Just write #Service or #Component annotation before class name. for example:
XML based:
<bean ID="id name" class="com.example.Employee">
Annotation:
#Service or #Component
class Employee{
}
And, add #ComponentScan("Give the package name"). This is the best approach.
I have a scenario configuring Spring Security on embedded Jetty which seems to be somewhat solved if I make use of JavaConfig to configure the Jetty server.
As a result, it's looking like JavaConfig rather than XML might be the better option for large chunks of the project. However, there are some niceties in the XML namespaces, like <context:component-scan /> which aren't readily available in a #Configuration setting.
I have discovered that ApplicationContextAware is honored for #Configuration classes, so the following is possible
#Configuration
public class FooConfig implements ApplicationContextAware {
#Override
public void setApplicationContext(ApplicationContext applicationContext) {
((AnnotationConfigApplicationContext) applicationContext).scan("org.example");
}
}
The alternative, which is documented, is to have the #Configuration class use an #ImportResource annotation and pull in an existing XML file:
#Configuration
#ImportResource("applicationContext-withComponentScan.xml")
public class BarConfig {}
I guess the question is "Is it bad form to abuse ApplicationContextAware in this way, or is it really not abuse"? Something just feels oddly dirty about the approach so I'd not be surprised if the Spring guys had covered this in some way or another that I've not spotted.
For the interested, the problem relates to scanning a Jersey setup with #Resource and #Provider classes that I'd rather not have to manually manage entries in a class/XML configuration.
Now that Spring 3.1 is ready and out, you can safely use #ComponentScan if you are on Spring 3.1. It's not only for Spring MVC as one of the outdated answers mentions. You can use it as follows:
#Configuration
#ComponentScan({"com.foo.bar", "org.foo.bar"})
public class AppConfig{ /** config code */ }
Here is the documentation http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/ComponentScan.html
Is it bad form to abuse ApplicationContextAware in this way, or is it really not abuse
Yes, this is bad form. If you're going to fetch things out of the context manually, you may as well not bother with dependency injection in the first place.
However, your second option (#ImportResource("applicationContext-withComponentScan.xml")) is a good one - this is current best practice when you want to use these XML macros in combination with annotation-style config.
A third option is to use the current milestone build of Spring 3.1, which adds a way of doing these things all in Java, using #Feature. This is not yet production-ready, though.
Check this link out as well. It is a bit more specific (for a web application) but it has a very nice code example for the scanning, specifically: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/EnableWebMvc.html
from that link:
#ComponentScan(basePackages = { "org.example"} )
So in the latest version of Spring we are able to use the #Configuration annotation to setup our configurations for Spring. Now in JavaConfig it is possible to use the #AnnotationDrivenTx (#AnnotationDrivenTx Reference Link) annotation to setup transactions in our Config class. But since JavaConfig has been decommissioned I was wondering if anyone knew how to setup something similar without JavaConfig and without needing to add anything to the application-context.xml. Here is what I basically have for my Config class
#Configuration
#ImportResource("config/application-context.xml")
public class Config {
public #Bean DataSource dataSource() {
//get and return datasource
}
public #Bean Service1 getService1() {
//return service1Impl
}
}
And I'd like to make Service1 transactional. If anyone has any ideas on how to do this or if this is just not possible please let me know.
Thanks!
You can now use #EnableTransactionManagement.
See this post for more details: http://blog.springsource.com/2011/06/10/spring-3-1-m2-configuration-enhancements/
It seems like it isn't possible according to this forum post:
there may be a more first-class
mechanism for enabling
annotation-driven TX in #Configuration
classes in Spring 3.1, but in the
meantime, the recommended approach is
to use #ImportResource to include a
snippet of XML that declares
<tx:annotation-driven/>
Wait: but you seem to have an XML context anyway. Why not add <tx:annotation-driven/> to it and use #Transactional?
Take a look at http://blog.springsource.com/2011/02/17/spring-3-1-m1-featurespec. Spring 3.1's FeatureSpecification classes such as TxAnnotationDriven are designed to solve exactly the problem described above.