springboot配置方式
第一步:再com.pp.springboothelloworld中创建service包,然后创建HttpService类
package com.pp.springboothelloworld.service;
public class HelloService {
}
第二步:再com.pp.springboothelloworld中创建config包,然后创建Myconfig类
package com.pp.springboothelloworld.config;
import com.pp.springboothelloworld.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Myconfig {
@Bean
public HelloService helloService(){
System.out.println("@bean给容器添加组件");
return new HelloService();
}
}
在Myconfig类中使用@Configuration注解,然后再定义一个返回类型为HelloService 的helloService()方法,并且用@Bean注解,返回是返回一个new HelloService()
第三步:再测试类中写测试方法
@Autowired
ApplicationContext ioc;
@Test
public void hello(){
boolean helloService = ioc.containsBean("helloService");
System.out.println(helloService);
}
测试方法中,测试方法外对ApplicationContext ioc使用了 @Autowired注解。方法里面调用了ioc.containsBean(“helloService”),这里用来寻找Myconfig类中helloService()方法.如果Myconfig中没有该方法就返回false,如果找到该方法就执行并且返回true.
第四步:测试
如图所示,测试方法中成功找到Myconfig类中的helloService方法,并且还执行方法里面的内容,最终返回一个true.相反我们运行一个Myconfig没有的方法,就会返回false。
spring配置方式
第一步:再resource创建beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.pp.springboothelloworld.service.HelloService"/>
</beans>
这里的中id使用service类中的小写,class写com.pp.springboothelloworld.service.HelloService。
第二步:在主配置类SpringBootHelloworldApplication中使用注解@ImportResource(locations = “classpath:beans.xml”)用来读取上面一步beans.xml的内容
第三步:在HelloService ,下写一个sava()方法,模拟数据库的保存
package com.pp.springboothelloworld.service;
public class HelloService {
public void save(){
System.out.println("保存");
}
}
第四步:在测试类中重新定义一个测试方法
hello1()
@Test
public void hello1(){
HelloService bean =(HelloService) ioc.getBean("helloService");
}
第五步:测试结果
源码地址:https://gitee.com/yangforever/project-learning/tree/master/demo/SpringBoot/spring-boot-helloworld2