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的引用对象
- 运行结果
- 写在最后
SpringBean的创建和注入有三种,XML、注解、java配置文件。
因为XML配置较为繁琐,现在大部分开始用注解和java配置,一般什么时候用注解或者java配置呢?
基本原则是:全局配置用java配置(如数据库配置,MVC,redis等相关配置),业务Bean的配置用注解(@Service @Component@Repository@Controlle)。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步