一.xml配置文件形式:
1.类的实现:
(1).UserDao:
public class UserDao{
....
}
(2).UserService:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) { //此处有set方法——set注入
this.userDao = userDao;
}
...
}
(3).Test测试类:
public class Test{
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] { "classpath:/applicationContext.xml" });
UserService userService = ctx.getBean("userService");
userService.save("123");
}
2.xml配置文件:
<bean id="userServiceImpl" class="com.kedacom.service.UserServiceImpl">
<property name="userDao" ref="userDao" /> //注意改行的改变
</bean>
<bean id="userDao" class="com.kedacom.persistence.UserDaoImpl"/>
二.注解的形式:
(一).一级转变:属性的注解——@Autowired/@Resource
1.类的实现:
(1).UserDao:
public class UserDao{
....
}
(2).UserService:
1.对成员变量进行标注:
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao; //属性用了注解,不再需要set方法
...
}
2. 对方法进行标注:
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
...
}
(3).Test测试类:
public class Test{
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] { "classpath:/applicationContext.xml" });
UserService userService = ctx.getBean("userService");
userService.save("123");
}
2.xml配置文件:
<bean id="userServiceImpl" class="com.kedacom.spring.annotation.service.UserServiceImpl"/>
<!--注意此处少了属性userDao的配置,用@Autowired注解通过java反射获得-->
<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl"/>
<!--注意用了@Autowired后,UserDao类的Bean还是必须要配置,非常重要!-->
<context:annocation-config/>
//<!--使用属性注解必须在xml配置文件中添加这句话,用于开启注解装配方式-->
(二).二级转变:类的注解——@Controller/@Service/@Repository/@Component
1.类的实现:
(1).UserDao:
@Repository
public class UserDao{
....
}
(2).UserService:
@Service
public class UserManagerImpl implements UserManager {
@Autowired
private UserDao userDao; //属性用了注解,不再需要set方法
...
}
//注意:在3.2.6版本中,使用@Autowired给属性注入后,若该类上面没有类的注解(@Service/@Repository等),
//@Autowired下面会出现红线,即编译报错。(原因还未知!)
(3).Test测试类:
public class Test{
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] { "classpath:/applicationContext.xml" });
UserService userService = ctx.getBean("userService");
userService.save("123");
}
2.xml配置文件:
<!--注意此处对于之前的Bean的配置都已经没有了,直接用@Service和@Repository进行注入了--> <context:component-scan base-package="com.huaxia.service"/> <!--在使用类的注解之后,必须在spring的xml配置文件中添加上面这行,它用于自动检测和扫描 指定的包中哪些类使用了类的注解,然后将其实例化后放在Spring容器中-->
三.Scema的说明:
<!--涉及到注解的部分是:--> xmlns:context="http://www.springframework.org/schema/context" <!--之所以会用到这个因为在使用注解功能时有一个自动扫描beans和注解功能注册的配置。 如下:--> <context:component-scan base-package="com.huaxia.service"/>
相关链接: