spring注解开发

Spring注解开发
在spring中使用注解,我们必须在applicationContext.xml文件中添加一个标签
context:annotation-config/作用是让spring中常用的一些注解生效。
要使用contex名称空间,必须在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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 
        
        <context:annotation-config/>
</beans>

写接口

package com.itcast.annotation;

public interface IUserService {
    public void add();
}

完成bean注册操作
@Component

编写实现类

package com.itcast.annotation;

import org.springframework.stereotype.Component;

@Component("userService")
public class IUserServiceImpl implements IUserService {
    @Override
    public void add() {
        System.out.println("userService add...");
    }
}

测试:

package com.itcast.annotationTest;

import com.itcast.annotation.IUserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationTest {
    @Test
    public void test1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        IUserService userService = (IUserService) applicationContext.getBean("userService");
        userService.add();
    }
}

报错:
在这里插入图片描述

原因:如果你使用的是spring3.x那么不会出现这个错误,如果使用的是spring4.x会报错,原因是缺少jar包。
在这里插入图片描述
导入jar后运行还有错误
在这里插入图片描述
我们在applicationContext.xml文件中使用了一个标签 <context:annotation-config />,它代表的是可以使用spring的注解,但是我们在类上添加的注解,spring不知道位置。
要解决这个问题,我们可以使用<context:component-scan base-package=””>

修改applicationContext.xml配置文件

  <?xml version="1.0" encoding="UTF-8"?>
<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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
	
    <!--<context:annotation-config/>该标签配置完包扫描之后可以去掉-->
    <context:component-scan base-package="com.itcast.annotation"/>

</beans>

在这里插入图片描述
再测试:success
在这里插入图片描述
注解开发需要的jar包(测试)
在这里插入图片描述

扩展:
在spring2.5后为@Component添加了三个衍生的注解
@Repository 用于DAO层
@Service 用于service层
@Controller 用于表现层
对于我们的bean所处在的位置可以选择上述三个注解来应用,如果你的bean不明确位置,就可以使用@Component.

猜你喜欢

转载自blog.csdn.net/Marion158/article/details/85294980