Spring中常用注解
<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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><!-- <context:annotation-config /> --><context:component-scan base-package="com.zzt.test" /></beans>
?
?
IUserService.java
?
package com.zzt.test;public interface IUserService {public void service();}?
?
UserServiceImpl.java
?
package com.zzt.test;import org.springframework.stereotype.Service;@Servicepublic class UserServiceImpl implements IUserService {@Overridepublic void service() {System.out.println("service ...");}}?
?
Person.java
?
package com.zzt.test;public interface Person {void testPerson();}?
?
Man.java
?
package com.zzt.test;import org.springframework.stereotype.Component;@Component//("man")public class Man implements Person {@Overridepublic void testPerson() {System.out.println("===========man===========");}}?
?
Woman.java
package com.zzt.test;import org.springframework.stereotype.Component;@Component//("woman")public class Woman implements Person {@Overridepublic void testPerson() {System.out.println("===========woman=========");}}?
用于测试的类:TestAction.java
package com.zzt.test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;@Controllerpublic class TestAction {@Autowiredpublic IUserService userService;@Autowired@Qualifier("woman")private Person person;public void test() {userService.service();person.testPerson();}}?
程序入口:Demo.java
package com.zzt.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Demo {public static void main(String[] args) throws InterruptedException {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");TestAction action = (TestAction) context.getBean("testAction");action.test();}}?
?getBean的默认名称是类名(头字母小 写),如果想自定义,可以@Service(“aaaaa”)这样来指定,这种bean默认是单例的,如果想改变,可以使用 @Service(“beanName”) @Scope(“prototype”)来改变。可以使用以下方式指定初始化方法和销毁方法(方法名任意):?
@PostConstruct public void init() { ?
} ?
@PreDestroy public void destory() { ?
}?
?
关于更多注解的使用,参考:http://www.iteye.com/topic/295348