Spring基于注解的配置 - 基于 Java 的配置
本文内容纲要:Spring基于注解的配置 - 基于 Java 的配置
Spring 中为了减少 XML 配置,可以声明一个配置类类对 bean 进行配置,主要用到两个注解 @Configuration 和 @bean,例子:
首先,XML 中增加如下的配置来启动 java 配置:
<context:component-scan base-package = "com.shiyanlou.demo.config"/>
定义一个配置类,用 @Configuration 注解该类,等价于 XML 里的 beans,用 @Bean 注解方法,等价于 XML 配置的 bean,方法名等于 bean Id。创建包 com.shiyanlou.demo.config,然后依次创建 SpringConfig.java、Service.java 和 Client.java,代码如下:
SpringConfig.java:
package com.shiyanlou.demo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
@Bean
public Service service(){
return new Service();
}
@Bean
public Client client(){
return new Client();
}
}
Service.java:
package com.shiyanlou.demo.config;public class Service {
public String sayHello(){
return "HelloWord!";
}
}
Client.java:
package com.shiyanlou.demo.config;import org.springframework.beans.factory.annotation.Autowired;
public class Client {
@Autowired
Service service;
public void invokeService(){
System.out.println("client invoke :" + service.sayHello());
}
}
最后修改 App.java 的代码:
package com.shiyanlou.demo;import com.shiyanlou.demo.config.Client;
import com.shiyanlou.demo.config.SpringConfig;
import com.shiyanlou.demo.helloworld.HelloWorld;
import com.shiyanlou.demo.entity.Dog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Client client = context.getBean("client", Client.class);
client.invokeService();
}
}
运行
mvn compilemvn exec:java -Dexec.mainClass="com.shiyanlou.demo.App"
实验结果如下所示:
本文内容总结:Spring基于注解的配置 - 基于 Java 的配置
原文链接:https://www.cnblogs.com/sakura579/p/13965026.html
以上是 Spring基于注解的配置 - 基于 Java 的配置 的全部内容, 来源链接: utcz.com/z/296481.html