SpringBoot 推薦給容器中添加組件的方式,推薦使用全註解的方式
1、配置類 @Configuration ------>相當於 Spring 的配置文件
2、使用 @Bean 給容器中添加組----相當於原來的 <bean id="testService" class="com.it.xxxxxx"></bean>
增加一個空的 service 用於測試
/**
* @Classname TestService
* @date 2019/8/25 13:41
*/
public class TestService {
}
配置類:
import com.atguigu.springboot.service.TestService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Classname TestServiceConfig
* @date 2019/8/25 13:42
*/
@Configuration
public class TestServiceConfig {
@Bean
public TestService testService01(){
System.out.println("進入加載...");
return new TestService();
}
}
測試:
import com.atguigu.springboot.pojo.Person;
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;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot01HelloworldApplicationTests {
@Autowired
ApplicationContext ioc;
@Test
public void test01(){
//注入的id就是上面方法的名稱
System.out.println(ioc.containsBean("testService01"));
}
}
結果:(方法會執行)