This article mainly introduces two ways to explain spring configuration in detail: JAVA configuration and annotation configuration, which has a certain reference value. Interested friends can refer to it
As we all know, spring has started since 3.0 From now on, it is fully recommended to use the configuration method to write code. This method can indeed avoid a lot of XML in a previous project. After all, the readability of XML is really not very good, and once you can write JAVA, you can also write code. Knowing how to write XML is indeed quite troublesome
At present, there are generally two spring configuration methods: JAVA configuration and annotation configuration. So what is annotation configuration? What is JAVA configuration?
//注解配置: @Service @Component @Repository @Controlle
//JAVA配置 @Confirguration 相当于spring的配置文件XML @Bean 用到方法上,表示当前方法的返回值是一个bean
The difference between these two methods is that if you use annotation, you need to annotate the class in the Serivce layer and DAO layer to get spring's Dependency Injection:
package di; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; //注解配置 @Service public class UseFunctionService { @Autowired FunctionService functionService; public String sayHello(String word) { return functionService.toHello(word); } }
If you use java configuration, there is no need to write annotations on the class, just declare it directly in the configuration class:
package javaconfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JavaConfig { //通过这种方式,获得spring的依赖注入 @Bean public UseFunctionService useFunctionService () { return new UseFunctionService (); } }
There is no so-called advantage or disadvantage between these two methods. It mainly depends on the usage. Generally speaking, it is like this:
Involves global configuration, such as database-related configuration, MVC-related configuration, etc. Just use the JAVA configuration method
If it involves business configuration, use the annotation method.
The above is the detailed content of There are two ways to configure spring in JAVA: (JAVA configuration and annotation configuration). For more information, please follow other related articles on the PHP Chinese website!