Can we autowire a class instance in a custom Thread class?

how to autowire parameterized constructor in spring boot
spring boot autowired constructor
spring @autowired
spring autowire multiple beans of same type
@org.springframework.beans.factory.annotation.autowired(required=true) in spring boot
spring autowire interface multiple implementations
spring @autowired setter
autowired members must be defined in valid spring bean

I have class that extends Thread class like this below :

public class A extends Thread {  

    public void run() {
      System.out.println("in thread");
    }

}

I have a service class like this below :

@Service
public class Service {

    public void someMethod() {
      .....
    } 

}

How can I autowire a service class instance inside my thread class ?

The answer for your question is YES. You can use autowired in thread class.

Have a look at this thread

Can a class that is a Spring Bean also implement Runnable, What this annotation basically does is provide an instance of a class when you request it in for example an You can indicate a @Primary candidate for @ Autowired. Do not create your own instances; let Spring handle it. Let's just wrap up with a few rules to remember. First, an abstract class isn't component-scanned since it can't be instantiated without a concrete subclass. Second, setter injection is possible in an abstract class, but it's risky if we don't use the final keyword for the setter method.

You can make class A a Spring component and then inject the dependency:

@Component
class A extends Thread{  
    public void run()
    {
     System.out.println("in thread");
    }

}

That said, pay extra care to what you are doing inside the run()

Java: How to fix Spring @Autowired annotation not working issues , Here are 3 examples to show you how to do “threading” in Spring. that each request will return a new instance, to run each individual thread. Component; @Component @Scope("prototype") public class The below PrintTask2 is Spring managed bean, you can @Autowired any required beans easily. As you can see there is an @Autowired annotation in the 6th line and we expect that Spring inject a proper bean here. But pay attention to that the wired field is static. Below is an example MyConfig class used in the utility class. It requires to pass foo property.

You can definately autowire.

example is below.

@Component
class A extends Thread{

 @Autowired
 Service service;

 public void run(){
      System.out.println("HI");
     serivce.anyMethod();
 }

}

you should register your thread class in spring application context by @component,@service or creating bean by @bean in configuration class.

Spring and Java Thread example, byType : The byType mode injects the object dependency according to type. Now, let's create our Employee class, in which we will inject� We can avoid this by narrowing the implementation using a @Qualifier annotation: public class FooService { @Autowired @Qualifier("fooFormatter") private Formatter formatter; } When there are multiple beans of the same type, it's a good idea to use @Qualifier to avoid ambiguity.

Yes, you can autowire, as our colleagues have already suggested. However, I would like to stress one point: the class must be a spring bean. Spring can autowire something only if the class itself is managed by Spring.

Once you do that, you should understand that by default spring creates a bean by calling new A() during the initialization, but it won't call start for you. Another interesting insight is that this Thread will be created only once (by default all beans are singletons in spring) so if you want many instances of A you might want to declare it as Prototype Scope.

Autowiring in Spring, Autowiring beans into classes that Spring isn't managing has long been FileEntityListener class before we learned that we could not do that. We can separate the classes on the basis of the function of that class such that controllers, service, repository,entity. We may use other classes for our logic only not for the purpose of controllers,service etc.,on that occasion we could annotate that classes with @component. This will automatically register that class in the spring container.

There are many ways in which you can do it. Some of them are given below:

A. Using @Autowired with a member variable of Service:

@Component
public class A extends Thread {     
    @Autowired
    private Service service;

    public void run() {
      System.out.println("in thread");
    }
}

B. Using @Autowired with a constructor initializing a member variable of Service:

@Component
public class A extends Thread {         
    private Service service;

    @Autowired
    public A(Service service) {
        this.service = service;
    }

    public void run() {
      System.out.println("in thread");
    }
}

C. Using @Autowired with the setter method of Service:

@Component
public class A extends Thread { 
    private Service service;

    @Autowired
    public void setService(Service service) {
        this.service = service;
    }

    public void run() {
      System.out.println("in thread");
    }
}   

Do check https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-autowire for more details.

Autowiring Spring Beans Into Classes Not Managed by Spring , How can I inject Spring managed beans into POJO's and classes not managed by Spring? So, I wanted to create a custom logger (I chose to extend on My simple logger which contains the method infoUser(Object) which� There are different ways through which we can autowire a spring bean. autowire byName – For this type of autowiring, setter method is used for dependency injection. Also the variable name should be same in the class where we will inject the dependency and in the spring bean configuration file.

Super simple approach to accessing Spring beans from non-Spring , A bean is an object that is instantiated, assembled, and otherwise managed by a Spring Thus you can define beans external to your application classes by using Java rather See Using AspectJ to dependency-inject domain objects with Spring. For instructions on how to register this or any other custom scope, see the� Extend Thread class to create Threads. Suppose we have a class FileLoaderThread, which simulates the functionality of a file loader and it’s run() method sleeps for around 5 seconds. We can create this class by extending Thread class provided by the threading module i.e. # A class that extends the Thread class class FileLoaderThread(Thread):

5. The IoC container - Project Metadata API Guide, Spring allows you to inject a managed object (bean) as a dependency into another class UserService { @Autowired(constructor="specify constructor for UserRepository As we stated earlier, to do this, we look into UserRepository itself and its creation point, not UserService. //have a custom annotation What this annotation basically does is provide an instance of a class when you request it in for example an instance variable of another class. You can do things like: @Autowired MyClass myClass; This causes myClass to automagically be assigned an instance of MyClass if certain requirements are met.

How to Autowire a Bean That Requires Constructor , Agree with @ericW's comment, and just want to add remember you can use initializers to keep your code compact: @Autowired private Converter converter;. or When you autowire a prototype bean, Spring will initialize a new instance of the bean. If you autowire the bean in multiple places, then Spring will create a new instance for every place you autowire the bean. Let us demonstrate this behavior by creating a test bean and a spring test where we autowire our test beans. Let us start with our test

Comments
  • Pri_stack - If one of the answers resolved your issue, you can help the community by marking it as accepted. An accepted answer helps future visitors use the solution confidently.