@Component @Controller @Service @Repository@Resourse这些全部是Spring提供的注解。
其中@Component用来表示把一个类纳入spring容器的管理中,使用如下:
@Component(value="test")
public class Test {
}
这样Test类就被Spring管理起来了。
而@Controller @Service @Repository其实只是@Component的细化,他们的作用也和@Component相同,只不过他们分别对应了程序中的
控制层、服务层、持久层。在使用时,一般使用这三个来管理类,因为这样项目分层更加清晰,使人一看就明白他是在那一层。使用如下:
@Controller (value="testAction")
public class TestAction {
}
@Service (value="testService")
public class TestService {
}
@Repository(value="testMapper")
public class TestMapper {
}
这样这三个类也会被Spring管理起来。
而最后的@Resourse是用来使用被Spring管理起来的类的注解,当你在某个类中想要使用一个已经被Spring管理的类时,使用方法如下:
public class TestAction {
@Resource(name="testService")
private TestService testService;
}
这样,名字为testService的类就被注入到此类中,不需要写set、get方法。
另外,当你注入的类实现了某一个接口时, private TestService testService;TestService 这个地方应该是接口。