@service 聲明該類爲一個bean,bean的名稱爲類名首字母小寫(customerService)spring
@Scope("prototype")則聲明爲一個原子類型,既每一個getbean方法返回一個實例app
package spring_service; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; /** * Created by luozhitao on 2017/8/10. */ @Service @Scope("prototype") public class CustomerService { public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } private String message; }
package spring_service; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by luozhitao on 2017/8/10. */ public class service_app { public static void main(String [] args){ ApplicationContext context=new ClassPathXmlApplicationContext("bean_service.xml"); CustomerService customerService=(CustomerService)context.getBean("customerService"); customerService.setMessage("spring server method"); System.out.println(customerService.getMessage()); } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="spring_service" /> </beans>
bean.xml看起來就很是簡練。this