1. 程式人生 > >Spring基礎學習(註解new例項物件)

Spring基礎學習(註解new例項物件)

一般自己寫的類就用@也就是註解例項化,匯入的jar架包就需要用bean例項化

applicationContext.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	
	<!-- 開啟自動掃描 -->
	<context:component-scan base-package="com.lanou.book.*"/>
</beans>

Book 類 

package com.lanou.book.domain;

import org.springframework.stereotype.Component;

@Component
public class Book {
	private String bookid;
	private String bookname;

}

BookServiceImpl

//括號中的bookService為new後的名字,不寫預設為類名第一字小寫
@Component("bookService")
public class BookServiceImpl implements BookService{
	
	@Autowired
	private BookDao bookDao = null;
	
	@Override
	public void save() {
		bookDao.save();		
	}

}

BookImpl類

@Component("bookDao")
public class BookImpl implements BookDao{

	@Override
	public void save() {
		System.out.println("我是測試滴");
		
	}

}

Test類

public class test {
	public static void main(String[] args) throws ServletException, IOException {
		ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
		BookDao bookDao = (BookDao) cxt.getBean("bookDao");
		bookDao.save();
		BookService bookService = (BookService) cxt.getBean("bookService");
		bookService.save();
		BookController studentController = (BookController) cxt.getBean("bookController");
		studentController.doGet();
	}

}