Spring中基于java的配置

时间:2023-03-09 03:20:49
Spring中基于java的配置

Spring中为了减少XML配置,可以声明一个配置类类对bean进行配置,主要用到两个注解@Configuration和@bean

例子:

  • 首先,XML中进行少量的配置来启动java配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="com.demo.config"/>
</beans>
  • 定义一个配置类,用@Configuration注解该类,等价于XML里的<beans>,用@Bean注解方法,等价于XML配置的<bean>,方法名等于beanId。代码如下:
@Configuration
public class SpringConfig {
@Bean
public Service service(){
return new Service();
}
@Bean
public Client client(){
return new Client();
}
}
  • 其他Bean代码:
public class Service {
public String sayHello(){
return "HelloWord!";
}
}
public class Client {
@Autowired
Service service;
public void invokeService(){
System.out.println("client invoke :" + service.sayHello());
}
}
  • 测试类
public class Test {

    public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Client client = context.getBean("client",Client.class);
client.invokeService();
}
}

加载XML中配置的beans和bean用:

ApplicationContext ctx = new ClassPathXmlApplicationContext("config/bean.xml");// 读取bean.xml中的内容
Counter c = ctx.getBean("client", Client.class);// 创建bean的引用对象

  • 运行结果

Spring中基于java的配置

  • 写在最后

SpringBean的创建和注入有三种,XML、注解、java配置文件。

因为XML配置较为繁琐,现在大部分开始用注解和java配置,一般什么时候用注解或者java配置呢?

基本原则是:全局配置用java配置(如数据库配置,MVC,redis等相关配置),业务Bean的配置用注解(@Service @Component@Repository@Controlle)。