我爱编程

Spring Bean管理(注解方式)

2018-06-27  本文已影响26人  沧海一粟谦

使用注解定义Bean

后面三个注解和@Component是等效的,是为了让标注类本身的用途清晰

举个栗子

除了引入spring的核心jar包,还要引入spring-aop

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.14.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.14.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.3.14.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.14.RELEASE</version>
    </dependency>

开启注解扫描(注意添加 context 约束)

<?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">
    
    <!--开启注解扫描-->
    <context:component-scan base-package="com.chen"/>

</beans>
/**
 * Spring的Bean管理的注解方式:
 *  * 传统方式需要去XML中配置<bean id="" class=""></bean>
 */
@Component("userService")
public class UserService {

    public String sayHello(String name){
        return "Hello" + name;
    }
}

测试

public class SpringTest{
    @Test
    public void test1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");

        String s = userService.sayHello("张三");
        System.out.println(s);
    }

Spring 的属性注入

@Repository("userDao")
public class UserDao {

    public void save(){
        System.out.println("DAO中保存用户...");
    }
}
@Service("userService")
public class UserService {
    /** 普通属性注入 ,有set方法的要注解在set方法上**/ 
    @Value("梅西")
    private String name;

    /** 注入userDao **/
 /* @Autowired
    @Qualifier("userDao") */
    @Resource(name="userDao")
    private UserDao userDao;

    public String sayHello(String name){
        return "Hello" + name;
    }
    
    public void save(){
        System.out.println("Service中保存用户...");
        userDao.save();
    }
}
@Test
    public void test2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = (UserService) applicationContext.getBean("userService");

        userService.save();
    }

输出:DAO中保存用户...
         Service中保存用户...

其他注解

XML与注解的整合开发

上一篇下一篇

猜你喜欢

热点阅读