创建接口:
MessageService.java
package com.my.web.service;
/**
* Created by yexianxun on 2017/2/20.
*/
public interface MessageService {
String getMessage();
}
UserService.java
package com.my.web.service;
/**
* Created by yexianxun on 2017/2/21.
*/
public interface UserService {
void addUser();
}
MessagePrinter.java
package com.my.web;
import com.my.web.service.MessageService;
import com.my.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by yexianxun on 2017/2/20.
*/
@Component
public class MessagePrinter {
final MessageService messageService;
@Autowired
public MessagePrinter(MessageService messageService) {
this.messageService = messageService;
}
@Autowired
private UserService userService;
public void printMessage() {
System.out.println(messageService.getMessage());
userService.addUser();
}
}
UserServiceImpl.java
package com.my.web.service.impl;
import com.my.web.service.UserService;
import org.springframework.stereotype.Component;
/**
* Created by yexianxun on 2017/2/21.
*/
@Component
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("add a user");
}
}
Application.java
package com.my.web;
import com.my.web.service.MessageService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
/**
* Created by yexianxun on 2017/2/20.
*/
@Configuration
@ComponentScan
public class Application {
@Bean
MessageService mockMessageService() {
return new MessageService() {
@Override
public String getMessage() {
return "hello world";
}
};
}
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Application.class);
MessagePrinter printer = applicationContext.getBean(MessagePrinter.class);
printer.printMessage();
}
}
@Controller、@Service、@Component、@Repository主要替换bean在xml中定义,而是通过以上注解定义。这四个主要区别:
@Controller 主要标识控制层类
@Service 主要标识业务层类
@Repository 主要标识数据访问层类
@Component 主要标识组件类
四个注解对应的BeanDefinition会有差异,但是功能是一样的。
@ComponentScan 注解与配置文件中 <context:component-scan base-package="com.adtime.bullbat.client"/>
相似。