通过@Bean注解将Bean注入spring容器

package com.edu.spring.config;/**
 * @author n00444323
 * @date 2019/1/15 12:12
 */

import com.edu.spring.config.bean.AnimalBean;
import com.edu.spring.config.bean.CatBean;
import com.edu.spring.config.bean.DogBean;
import com.edu.spring.config.factorybean.RunnableFactoryBean;
import com.edu.spring.mvcbean.UserController;
import com.edu.spring.mvcbean.UserDao;
import com.edu.spring.mvcbean.UserService;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @param
 * @return
 * @throws
 */

@Configuration
public class MyConfig
{

    @Bean
    public UserDao createUserDao ()
    {
        return new UserDao();
    }

    @Bean
    public UserDao createUserDao2 ()
    {
        return new UserDao();
    }



}

 

package com.edu.spring.mvcbean;/**
 * @author n00444323
 * @date 2019/1/15 15:58
 */

import com.sun.org.apache.bcel.internal.generic.JSR;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.lang.annotation.Inherited;

import javax.annotation.Resource;
import javax.inject.Inject;

import jdk.nashorn.internal.objects.annotations.Getter;
import jdk.nashorn.internal.objects.annotations.Setter;

/**
 * @param
 * @return
 * @throws
 */
@Service
public class UserService
{

    @Autowired
    @Qualifier(value = "createUserDao2")  //使用Qualifier指定bean对象
    private  UserDao userDao;


    @Resource  //JSR 250 提供的注入能力
    @Qualifier(value = "createUserDao2")
    private  UserDao userDao1;


    @Inject
    @Qualifier(value = "createUserDao2")
    private  UserDao userDao2;

    private  void show(){
        System.out.println("UserService...userDao");
    }

    @Override
    public String toString()
    {
        return "UserService{" +
                "userDao=" + userDao +
                ", userDao1=" + userDao1 +
                ", userDao2=" + userDao2 +
                '}';
    }
}

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐