使用@Configuration和@Bean註解,代替在Spring的.xml配置文件中配置Bean
一.目錄結構
二.相關代碼
TestService.java
package com.SpringBoot.hello.service;
public interface TestService {
public void test();
}
TestServiceImpl.java
package com.SpringBoot.hello.service.impl;
import com.SpringBoot.hello.service.TestService;
public class TestServiceImpl implements TestService {
@Override
public void test() {
System.out.println("TestService");
}
}
AppConfig
package com.SpringBoot.hello.configure;
import com.SpringBoot.hello.service.TestService;
import com.SpringBoot.hello.service.impl.TestServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* spring4.x支持用@Configuration和@Bean
* 代替之前的xml配置
* 代碼相當於之前的
* <beans>
* <bean id="myService" class="com.SpringBoot.hello.service.impl.TestServiceImpl"/>
* </beans>
*/
@Configuration
public class AppConfig {
//這裏的方法名就是之前xml中需要配置的id
@Bean
public TestService myService(){
System.out.println("配置類");
return new TestServiceImpl();
}
}
測試的類:
package com.SpringBoot.hello;
import com.SpringBoot.hello.service.TestService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 單元測試
* 爲了提前發現缺陷並且在後續開發中避免
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloApplicationTests {
@Autowired
ApplicationContext ioc;
@Test
public void contextLoads() {
//是否包含id名爲myService的Bean
boolean flag=ioc.containsBean("myService");
System.out.println(flag);
// 在Spring容器中獲取Bean對象
TestService testService=ioc.getBean(TestService.class);
testService.test();
}
}
三.運行測試類,並且在控制檯查看結果
打印的結果說明我們已經成功的將bean拿到,代替了傳統的需要xml中配置bean的方式。
關注公衆號,獲取更多資源
每天進步一點點,開心也多一點點