Spring4 註解配置bean

Spring4 註解配置bean

特定組件包括:

  • @Component :標識一個受 Spring 管理的組件
  • @Respository :標識持久層組件
  • @Service :標識業務層組件
  • @Controller :標識表現層組件

當在組件類上使用註解之後,需要在 Spring 的配置文件中聲明:< context:component-scan >

           屬性:

  • base-package=“com.java.spring” // 指定 IOC 容器掃描的包
  • resource-pattern=“service/*.class” //表示只掃描service下的類,用於指定掃描資源
        子節點:
  • < context:exclude-filter type=“annotation” expression=“org.springframework.stereotype.Service”/>
    表示指定排除 org.springframework.stereotype.Service 這個組件
  • < context:include-filter type=“annotation” expression=“org.springframework.stereotype.Service”/>
    表示指定使用 org.springframework.stereotype.Service 這個組件,但需要將屬性 use-default-filters=“true” 改爲 false 才能生效,該屬性表示使用默認的 filter 默認爲值 true

使用 @Autowired 自動裝配 Bean

  • @Autowired 註解自動裝配類型相兼容的單個 Bean
  • 可以在 構造器、普通字段,和一切有參數的方法上使用
  • 默認情況下使用 @Autowired 註解的屬性需要被Spring所管理,當Spring找不到相匹配的Bean時,會拋出異常,若要某一屬性允許不被設置,可以設置 註解的 required 屬性爲 false 即可
    例:
@Controller
public class TestController {

    @Autowired
    private TestService testService;

    public void execute(){
        System.out.println("TestController execute...");
        testService.add();
    }
}
@Service
public class TestService {
    @Autowired()
    private TestRepository testRepository;
    
    public void add(){
        System.out.println("TestService add...");
        testRepository.save();
    }

}

@Repository("testRepository")
public  class TestRepositoryImpl implements TestRepository {
    @Autowired(required = false)
    private Test test;
    @Override
    public void save() {
        System.out.println("testReopsitory save...");
        System.out.println(test);
    }
}
// @Component
public class Test {}
public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        TestController tc = (TestController) ctx.getBean("testController");
        System.out.println(tc);
        tc.execute();
    }
}

運行結果爲:

com.java.spring.controller.TestController@6d3af739
TestController execute...
TestService add...
testReopsitory save...
null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章