Spring中常用注解

 

@Service用于标注业务层组件

@Controller用于标注控制层组件(如struts中的action)

@Repository用于标注数据访问组件,即DAO组件

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注

 

如下是一个测试例子:

applicationContext.xml

 

 

<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;

@Service
public class UserServiceImpl implements IUserService {

	@Override
	public 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 {

	@Override
	public void testPerson() {
		System.out.println("===========man===========");
		
	}

}

 

 

Woman.java

package com.zzt.test;

import org.springframework.stereotype.Component;

@Component//("woman")
public class Woman implements Person {

	@Override
	public 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;

@Controller
public class TestAction {

	@Autowired
	public 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

猜你喜欢

转载自zhangzhenting.iteye.com/blog/1829010