SpringBoot bean注入的三种方式

搜索maven依赖

https://search.maven.org/

 

spring bean注入的三种方式:

方式一:

@Controller(value = "my_userController")
@Repository(value = "userDao")
@Service
@Repository(value = "userDao")
package com.edu.spring.mvcbean;/**
 * @author n00444323
 * @date 2019/1/15 15:58
 */

import com.oracle.webservices.internal.api.databinding.DatabindingMode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

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

/**
 * @param
 * @return
 * @throws
 */
//一般用在展示层
@Controller(value = "my_userController")
public class UserController
{

    @Autowired
    public UserImpl userImpl;

    @Override
    public String toString()
    {
        return "UserController{" +
                "userImpl=" + userImpl +
                '}';
    }
}
package com.edu.spring.mvcbean;/**
 * @author n00444323
 * @date 2019/1/15 15:59
 */

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

/**
 * @param
 * @return
 * @throws
 */
@Component
public class UserImpl
{

    @Autowired
    private UserService userService;

    @Override
    public String toString()
    {
        return "UserImpl{" +
                "userService=" + userService +
                '}';
    }

    public void show()
    {
        System.out.println("UserImpl...userService..");
    }
}

AnnotationConfigApplicationContext  存储bean对象

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

import com.edu.spring.config.MyBean;
import com.edu.spring.config.MyConfig;
import com.edu.spring.config.factorybean.Jeep;
import com.edu.spring.config.factorybean.RunnableFactoryBean;
import com.edu.spring.mvcbean.UserController;
import com.edu.spring.mvcbean.UserDao;
import com.edu.spring.mvcbean.UserImpl;
import com.edu.spring.mvcbean.UserService;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @param
 * @return
 * @throws
 */
public class APP
{

    public static void main(String[] args)
    {


        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class, UserController.class, UserService.class, UserImpl.class,UserDao.class);

        //当系统有多个bean对象后,可以使用context.getBeansOfType过去所有该类型的bean对象
        System.out.println(context.getBeansOfType(UserController.class));
        //通过名字获取bean对象
        System.out.println(context.getBean("my_userController"));
        System.out.println(context.getBean("createUserController"));

        //当UserImpl.class类型有且仅有一个bean对象后,可以使用UserImpl.class过去该bean对象
        System.out.println(context.getBean(UserImpl.class));
        System.out.println(context.getBean(UserService.class));
        System.out.println(context.getBean(UserDao.class));


        context.close();


    }

}

方式二:

 

 

你可能感兴趣的:(SpringBoot)